Custom data attributes with multiple elements - javascript

I'm trying to make a custom data attributes on my website in lightbox. I just made it for one element in Javascript and it works fine but I want to make it works in multiple elements.
How it works now: I have "a" element with id="image-1" and I want to make that javascript will recognise id image-2,3,4... and show correct data from custom attributes. Note that I can't use onclick because it makes that lightbox stops work.
Here is HTML:
<div class="col-xs-12 col-sm-4 col-md-3 col-lg-3">
<div class="thumbnail grid-wrapper thumbnail-single">
<a id="image-1" href="img/photo2.jpeg" data-tags="<li>t31232est</li> <li>test</li>" data-fb="http://test1.pl" data-tt="http://test2.pl" data-gplus="http://te23432st3.pl" data-lightbox="roadtrip" data-title="This is a caption. This is a caption This is a caption This is a caption"><img src="img/photo2.jpeg" class="img-responsive" alt="..."></a>
</div>
</div>
<div class="col-xs-12 col-sm-4 col-md-3 col-lg-3">
<div class="thumbnail grid-wrapper thumbnail-single">
<a id="image-2" href="img/photo3.jpg" data-tags="<li>test</li> <li>test</li>" data-fb="http://test55.pl" data-tt="http://test253342.pl" data-gplus="http://tes32423t3.pl" data-lightbox="roadtrip" data-title="This is a caption. This is a caption This is a caption This is a caption"><img src="img/photo3.jpg" class="img-responsive" alt="..."></a>
</div>
</div>
Here is JS:
var global = document.getElementById('image-1');
var tagList = global.getAttribute('data-tags');
var facebook = global.getAttribute('data-fb');
var twitter = global.getAttribute('data-tt');
var gplus = global.getAttribute('data-gplus');
$('<div id="lightboxOverlay" class="lightboxOverlay"></div><div id="lightbox" class="lightbox"><div class="lb-outerContainer"><div class="lb-container"><img class="lb-image" src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" /><div class="lb-nav"><a class="lb-prev" href="" ></a><a class="lb-next" href="" ></a></div><div class="lb-loader"><a class="lb-cancel"></a></div></div></div><div class="lb-dataContainer"><div class="lb-data"><div class="lb-details"><ul class="tag-list">' + tagList +'</ul><br/><span class="lb-caption"></span><span class="lb-number"></span></div><div class="lb-closeContainer">' +
'<ul class="social-list"><li><img src="img/fb_circle_white.png" class="img-responsive"></li><li><img src="img/tt_circle_white.png" class="img-responsive"></li><li><img src="img/gplus_circle_white.png" class="img-responsive"></li></ul><a class="lb-close"></a></div></div></div></div>').appendTo($('body'));
I'm trying to make it works on Lightbox Plugin (http://lokeshdhakar.com/projects/lightbox2/)
UPDATE
I just used function in onclick and when I'm testing it, it shows correct IDs. But still can't put it into getElementByID as a string.
id="image-1" onclick="GetID(this.id)"
window.GetID = function(elem_id){
alert(elem_id);
}
var global = document.getElementById(GetID());
var tagList = global.getAttribute('data-tags');
var facebook = global.getAttribute('data-fb');
var twitter = global.getAttribute('data-tt');
var gplus = global.getAttribute('data-gplus');
UPDATE 2:
Almost done. I've made my variables global. Console log shows correct ID and other data attribs. Problem is when I'm trying to put result into html in javascript. Here is example.
<ul class="social-list"><li><img src="img/fb_circle_white.png" class="img-responsive"></li>
+ current JS:
id="image-1" onclick="window.GetID(this.id)"
var global;
var tagList;
var facebook;
var twitter;
var gplus;
window.GetID = function(elem_id){
console.log(elem_id);
global = document.getElementById(elem_id);
console.log(global);
tagList = global.getAttribute('data-tags');
console.log(tagList);
facebook = global.getAttribute('data-fb');
console.log(facebook);
twitter = global.getAttribute('data-tt');
console.log(twitter);
gplus = global.getAttribute('data-gplus');
console.log(gplus);
}
+ image of console response.

A good solution would be to get the id attribute of 'a' element when clicking it put it in a var and use it to get data attributes.
Assuming 'a' elements are inside a div '#container' here is my solution
$('#container a').click(function(){
var image_id = '#' + $(this).attr('id');
var tagList = $(image_id).data('tags');
var facebook = $(image_id).data('fb');
var twitter = $(image_id).data('tt');
var gplus = $(image_id).data('gplus');
});

not sure if I am understanding correctly. But if the id of the divs are consistent, meaning image-1, image-2, image-3,... and so on, you could use and expression selector and loop through the number of elements in that array to add/append your dynamic html inside those divs without using a click event to get the id. Ex -
var array_of_divs = $("div[id^=image-]") // this gives you an array of all the element having the id starting with 'image-'
further you can loop though the length of this array and add your dynamic html based on the id of the parent : ("image-"+counter_variable])
let me know if this helps.

Related

How can I add the same XML tags multiple times, with different content?

I have some problems with my code. I want to create an XML Document with JQuery / JavaScript. I am now at the point, where I want to create a few Tags and populate them each with the same tags but different content inside the tags.
Here is the code for better understand
function setItems(xmlDoc, channelTag){
const itemList = [];
const itemTitle = xmlDoc.createElement("title");
const itemLink = xmlDoc.createElement("link");
const itemGuid = xmlDoc.createElement("guid");
const itemMediaContent = xmlDoc.createElement("media:content");
const itemMediaDescription = xmlDoc.createElement("media:description");
itemList.push(itemTitle, itemLink, itemGuid, itemMediaContent, itemMediaDescription);
for (var i = 0; i < jsonObj.length; i++){
var item = xmlDoc.createElement("item");
channelTag.appendChild(item);
//Populate the <item> with the tags from "itemList" and content from "jsonObj"
$.each(itemList, function(index) {
$(channelTag).children('item')[i].appendChild(itemList[index]).textContent = jsonObj[0].title;
})
}
}
The Output of the code looks like this:
<item></item>
<item></item>
<item>
<title>Something</title>
<guid>Something</guid>
<link>Something</link>
<media:content>Something</media:description>
<media:description>Something</media:description>
</item>
It always populates the last item-Tag but not the ones above. What I want is that every item-Tag has the same child-Tags (e.g. title, link, guid and so on). Is there something i am missing some unique tags or something like that?
Edited:
Here is some minimal HTML and XML. The values for the function "xmlDoc" and "channelTag" just contains some Document Elements, where my items should be appended, like so:
<rss>
<channel>
<title>SomeTitle</title>
<atom:link href="Link" rel="self" type="application/rss+xml"/>
<link>SomeLink</link>
<description>SomeDesc</description>
<item></item>
<item></item>
<item></item>
</channel>
</rss>
<div class="col-5 col-sm-5 col-lg-3 order-2 count">
<a class="guid1"><img class="card-img image1"></a>
</div>
<div class="col-7 col-sm-7 col-lg-5 order-2">
<div class="card-body">
<a class="guid1">
<h5 class="card-title title1 overflow-title"></h5>
</a>
<p class="card-text body1 text-body overflow-body"></p>
<div class="card-body subtitle">
</div>
</div>
</div>
There are several issues with your code but the area we mostly want to focus on is this:
for (var i = 0; i < jsonObj.length; i++){
var item = xmlDoc.createElement("item");
channelTag.appendChild(item); // you're adding a node here
$.each(itemList, function(index) {
$(channelTag).children('item')[i].appendChild(... // and here
})
}
Instead of appending nodes multiple times per iteration, you should create and populate your node before add it it to channelTag.
Here's a way your could do it:
// use a "$" sign as a variable name prefix, so you know it's a Document Element and not a regular javascript variable
var $item = xmlDoc.createElement("item");
// you don't need jQuery for this iteration
itemList.forEach(function (item, index) {
$item.appendChild(itemList[index]).textContent = jsonObj[0].title;
});
// if "channelTag" is a Document Element, rename it "$channelTag"
$channelTag.appendChild(item);
Couple things about the code above:
you don't need jQuery, use forEach instead
there is no way telling what type is channelTag. If it is a selector (of type string), use $(selector), but you are using the appendChild() method before, suggesting it's actually a Document Element. In that case you don't need to wrap it with $()
I don't have the context needed to test this code, so no guarantee it'll work out of the box. But try and re-read your code and go through it top-to-bottom. For each variable, describe its type and value. I found that to be helpful when I'm lost in code.

Trying to split an Alt tag in an Object and then place it all into an Array

I have some products on a page that I need to grab the Alt tag from. I need to turn them into an Object. After that they need to go into an Array.
I was thinking of creating a for loop to loop through the Alt tags, but I am stuck as to how to Split the Alt tag at the pipe '|'.I keep getting an Invalid or unexpected Token. This is code and below that is what I have.
Right at the end I have the jQuery version that works fine, but I want to know the Vanilla Javascript way. As I want to step away from jQuery and learn how to code better in Javascript.
<div class="product col-xl-3 col-lg-3 col-md-4 col-sm-6 col-12" alt="0016|AUX Cable|2.39|5m|Black|2|Tech-Aux">
<a href="/0016/product">
<img class="productImage" src="/static/store/images/products/download-10.jpg">
</a>
<a href="/0016/product">
<h3>AUX Cable</h3>
</a>
<h4 class="price">£2.39</h4>
<input type="button" class="button style_one addToCartOne" value="Add To Cart">
</div>
<div class="product col-xl-3 col-lg-3 col-md-4 col-sm-6 col-12" alt="0015|USB 2 Type A|3.49|10m|Black|300|Tech-Usb">
<a href="/0015/product">
<img class="productImage" src="/static/store/images/products/download_Jb4ucER.jpg">
</a>
<a href="/0015/product">
<h3>USB 2 Type A</h3>
</a>
<h4 class="price">£3.49</h4>
<input type="button" class="button style_one addToCartOne" value="Add To Cart">
</div>
Here is my code:
var products = document.querySelectorAll('.product');
for(var i=0; i<products.length; i++){
products[i].alt.split(“|”);}
Thank you for any advise. Also any help as to where I can look this up in the future would be great as well.
This is the jQuery code that works. And this is what I want to achieve in Javascript:
var products = [];
$.each($(".product"), function(){
var prodOb = {};
var prodDetails = $(this).attr("alt").split("|");
prodOb.id = prodDetails[0];
prodOb.name = prodDetails[1];
prodOb.price = prodDetails[2];
prodOb.brand = "Some Company";
products.push(prodOb)
})
console.log(products)
You're really close, you've done the big that people find tricky (using the DOM instead of jQuery to find the elements).
Two things:
You seem to have stopped in the middle. You have the code using jQuery to do this, and most of that code has nothing to do with jQuery, but you haven't used that code in your attempt.
You're using fancy quotes (“”), but JavaScript requires boring straight up-and-down quotes (").
If we just copy the code from the sample using jQuery into the code you've already written, and fix the quotes, use elements instead of products to conflict with the array you're creating, use a reasonable placement for }, and add a missing semicolon or two, we get:
var products = [];
var elements = document.querySelectorAll('.product');
for (var i = 0; i < elements.length; i++){
var prodDetails = elements[i].getAttribute("alt").split("|");
var prodOb = {};
prodOb.id = prodDetails[0];
prodOb.name = prodDetails[1];
prodOb.price = prodDetails[2];
prodOb.brand = "Some Company";
products.push(prodOb);
}
console.log(products);
Or we can use Array.prototype.map, but for one it isn't a lot more concise:
var products = Array.prototype.map.call(
document.querySelectorAll('.product'),
function(element) {
var prodDetails = elements.getAttribute("alt").split("|");
return {
id: prodDetails[0],
name: prodDetails[1],
price: prodDetails[2],
brand: "Some Company"
};
}
);
console.log(products);
Note: We have to use .getAttribute("alt") instead of .alt because the HTML is invalid. div elements have no alt attribute. I have to admit in the first version of this question I didn't look at the HTML and assumed that it was valid, where the alt attribute is used on an img element (which has the .alt property).

Jquery Classes and InnerHtml

So what I'm doing is pulling battery voltage and the state of a battery from a Mysql database processing the data in data.php and putting that into a Json array all that is fine. When I get to the Javascript side I get stuck.
2 Questions:
Question 1: How do insert the value into id voltage in html without removing the span?
HTML Code:
<div id="voltState" class="tile-box bg-green">
<div class="tile-header">
Battery Status
<div class="float-right">
<i class="glyph-icon icon-bolt"></i>
Green
</div>
</div>
<div class="tile-content-wrapper">
<i class="glyph-icon icon-database"></i>
<div id="voltage" class="tile-content">
<span>volts</span>
</div>
</div>
</div>
Questions 2: class="tile-box bg-green"> I want to replace with the var status from the Javascript so it looks something like class="tile-box bg-(status var here)">
$(document).ready(function() {
sensorData();
});
function sensorData(){
$.ajax({
type:'GET',
url:"data.php",
data:"json",
success:function(sensor) {
//document.write(sensor);
var volt = sensor[0];
var status = sensor[1];
var date = sensor[2];
document.getElementById('voltage').innerHTML = (volt);
$("#voltState").toggleClass('bg-green bg-(STATUS VAR HERE??)');
},
dataType:'json'
});
}
setInterval(sensorData, 3000);
You can use $("#voltage").append(volt) or $("#voltage").prepend(volt) based on if you want the span before or after the value. In this case I assume you want the span after the volt so you can use the second code. If you would like the value inside a new span you can also use:
$("#voltage").prepend($("").text(volt));
You can store the previous status value in a variable lets say pastStatus. So once you have set
$("#voltState").removeClass('bg-'+pastStatus).addClass('bg-'+status);
pastStatus = status
Note: toggleClass is used when you want to switch between adding and removing the same class. It can't be used in this case since you want to add a class and remove another.
document.getElementById('voltage').appendChild(volt);
or
document.getElementById('voltage').innerHTML = '<span>'+volt+'</span>';

Get values from elements inside DIV

I need to get values inside div on clicking a button, wich locates inside this div. Here is the html structure:
<div class="products__item">
<div class="products__content">
<a class="products__title" href="#">Altec Lansing Octiv Duo M202 акустическая система акустическая система</a>
<div class="products__priceholder">
<p class="products__price"><strong>86 590</strong> руб.</p>
<small class="products__id">ID. 10906</small>
</div>
<p class="exist">В наличии</p>
<div class="products__buttonholder">
Купить
</div>
</div>
</div>
When I click on .button-buy-modal, I need to get values from .products__title .products__price and .products__id, but the problem is that we have a lot same div's (product cards), and a lot of buttons inside them. I think that I should use something like $(this), but actually I don't know how.
I'm trying to test something like this, but it doesn't work:
$("a.button-buy-modal").click(function () {
$(this).find().closest('.products__priceholder').addClass('test1');
})
Here is a solution:
$("a.button-buy-modal").click(function () {
var prTitle = $(this).parent().parent().children('.products__title').html();
var prPrice = $(this).parent().parent().children('.products__priceholder').children('.products__price').children('strong').html();
var prId = $(this).parent().parent().children('.products__priceholder').children('.products__id').html();
var prImage = $(this).parent().parent().parent().children('.products__imageholder').children('.products__thumbnail').attr('src');
console.log(prTitle);
console.log(prPrice);
console.log(prId);
console.log(prImage);
})
$(this).parent().parent().find('.products__price').text()
will give you this - "86 590 руб."
$(this).parent().parent().find('.products__price').html()
will give you this -- "<strong>86 590</strong> руб."
To learn more about it as in how you can select any particular DOM element and read it or manipulate it etc, read here - http://api.jquery.com/category/selectors/
You can add an id to your parent div or use eq(x) to select the right group.
<div id="mydiv1" class="products__item">
<div class="products__content">
<a class="products__title" href="#">Altec Lansing Octiv Duo M202 акустическая система акустическая система</a>
<div class="products__priceholder">
<p class="products__price"><strong>86 590</strong> руб.</p>
<small class="products__id">ID. 10906</small>
</div>
<p class="exist">В наличии</p>
<div class="products__buttonholder">
Купить
</div>
</div>
</div>
Then with jQuery:
var title = $('#div1 .products__title').html();
/// OR
var title = $('.products__item:eq(0) .products__title').html();
var price = $('#div1 .products__price').html();
/// OR
var price = $('.products__item:eq(0) .products__price').html();
price = price.replace(/<[^>]+>/g, ""); // regex to remove tags
EDIT
If you want to use .closest(), you don't need .find()
$("a.button-buy-modal").click(function () {
$(this).closest('.products__priceholder').addClass('test1');
});
Thank's all for advices, I found a solution:
$("a.button-buy-modal").click(function () {
var prTitle = $(this).parent().parent().children('.products__title').html();
var prPrice = $(this).parent().parent().children('.products__priceholder').children('.products__price').children('strong').html();
var prId = $(this).parent().parent().children('.products__priceholder').children('.products__id').html();
var prImage = $(this).parent().parent().parent().children('.products__imageholder').children('.products__thumbnail').attr('src');
console.log(prTitle);
console.log(prPrice);
console.log(prId);
console.log(prImage);
})

How to use specific data from arrays - Example of click

I have the following JQuery code:
var test = new Array();
$(".quiz_list_row").each(function(index){
// Gets the data necessary to show game chosen
$quiz_list_id = $(this).data("quizlistId");
$quiz_level_reached = $(this).data("quizlevelReached");
test.push($quiz_list_id,$quiz_level_reached);
$(this).click(function(){
alert("test: "+test);
});
});
The divs (using html5 to send data):
<div class="quiz_list_row" data-quizlist-id="1" data-quizlevel-reached="5">
<div class="inline quiz_list_cell" id="quiz_list_cell_row0_id1">Quiz 1</div>
<div class="inline quiz_list_cell" id="quiz_list_cell_row0_id2">Current level: 5</div>
</div>
<div class="quiz_list_row" data-quizlist-id="2" data-quizlevel-reached="7">
<div class="inline quiz_list_cell" id="quiz_list_cell_row1_id1">Quiz 2</div>
<div class="inline quiz_list_cell" id="quiz_list_cell_row1_id2">Current level: 7</div>
</div>
The problem is that I need to find out how to use the data in the array test when the user clicks on a specific row (I want to use $quiz_list_id and $quiz_level_reached).
Unless there is a specific reason you're extracting the attributes and putting them into an array, I think you're taking some unecessary steps to achieving what you want. Take away the complexity from this, you have access to the data attributes with the .data() method at any time you have access to the elements jQuery object, one of those times is within the click handler itself.
var quizRows = $(".quiz_list_row");
quizRows.click(function(event) {
var self = $(this);
//As the element clicked on has it's data attributes defined
//You would just need to retrieve it when the element is clicked on
var id = self.data('quizlist-id'),
level = self.data('quizlevel-reached');
console.log("id is " + id);
console.log("level is " + level);
}

Categories

Resources