jQuery append an img to every div - javascript

I am trying to display a thumbnail image with every thumb class, but currently I am getting the output below where the images are looping inside the href instead. The order of div, href and img must not change. It looks something like this jsfiddle but this isn't fully working of course...
currently getting:
<div class ='thumb'>
<a href="#" rel="1">
<img src="">
</a>
<img src="">
<img src="">
</div>
required output:
<div class ='thumb'>
<a href="#" rel="1">
<img src=>
</a>
</div>
<div class ='thumb'>
<a href="#" rel="1">
<img src="">
</a>
</div>
my loop:
var thumbnails = [];
$.each(data.productVariantImages,function(key, val){
thumbnails.push(val.imagePath);
});
for(var thumb in thumbnails) {
$('.thumb').append($('<img>').attr({
"src":[thumbnails[thumb]]
}));
}
am i looping it wrongly?
edit:
The thumbnails are part of a dynamic gallery where basically every time a user choose a different option in a dropdown list, the sources for the thumbs are supposed to change accordingly.
current html:
<div class="thumbnail"><?php
foreach($skuDetails['productVariantImages'] as $variantImage){
if(isset($variantImage) && $variantImage['visible']){
?>
<div class="thumb">
<a href="#" rel="1">
<img src="<?php echo $variantImage['imagePath']; ?>" id="thumb_<?php echo $variantImage['id']; ?>" alt="" />
</a>
</div> <?php }}?>
</div>
sample array of thumbnails:
["http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples_in_season.png",
"http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples_in_season.png"]
sample output:
<div class="thumbnail">
<div class="thumb">
<a href="#" rel="1">
<img src="http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples.png" id="thumb_323" alt="">
</a>
</div>
<div class="thumb">
<a href="#" rel="1">
<img src="http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples.png" id="thumb_323" alt="">
</a>
</div>
</div>

You need to use .each function on .thumb. Something like:
$(document).ready(function(){
$('.thumb').each(function(){
$(this).append($('<img>').attr({"src":[thumbnails[thumb]],}));
});
});

your loop is focused on wrong element. You append img tag to the thumb class. So, the img tags inside the same element. You should create div has thumb class inside the loop, and append it to the thumbnail div. That must like
var div = $(".thumbnail");
$.each(imageArray, function(index, value){
var elem = "<div class='thumb'><a href='#' rel='1'></div>";
div.append($elem);
$('.thumb').append("<img />").attr("src", value);
});
It may be wrong but you should watch the thumbnail element. I cannot write the code to test. But I think the logic must be like this.

If you want that exact structure, I made a demo using plain JavaScript. Enter a number and the thumbClone() function will generate that many. You could probably adapt this function with your existing code easily. I'm in rush, it probably needs refactoring, sorry. :-\
DEMO
function thumbClone(qty) {
var main = document.getElementById('main');
var aFig = document.createElement('figure');
var aLnk = document.createElement('a');
var aImg = document.createElement('img');
aLnk.appendChild(aImg);
aImg.src = "http://placehold.it/84x84/000/fff.png&text=THUMB"
aFig.appendChild(aLnk);
aLnk.setAttribute('rel', '1');
main.appendChild(aFig);
aFig.className = "thumb";
console.log('qty: ' + qty);
var thumb = document.querySelector('.thumb');
for (var i = 0; i < qty; i++) {
var clone = thumb.cloneNode(true);
thumb.parentNode.appendChild(clone);
}
}

You need to use each loop which will get each class rather than getting only one class below is syntax of each loop
$(selector).each(function(){
// do your stuff here
)};
in your case
$('.thumb a').each(function(){
// do your stuff here
$(this).append($('<img />').attr('src',[thumbnails[thumb]]);
)};

Looks like you need to create the entire div structure for each image.
Lets create the below structure dynamically using the max length of the image array and add the image src .
var thumbDivStart = "<div class ='thumb'><a href="#" rel="1">";
var thumbDivEnd = "</a></div>";
var thumbDiv = "";
for (i = 0; i < imageArray.length; i++) {
thumbDiv = thumbDivStart + "<img src="+imageArray[i]+"/>"+
thumbDivEnd;
//Here you can append the thumbDiv to the parent element wherever you need to add it.
}

Related

Put the image src from the clicked element image src and update data

I don't know how to explain this because I am an amateur.
I have a language menu with 6 languages: Es, Br, Fr, It, De, En
So, I have the default language selected EN and a dropdown with the rest of the images.
The question is: how can I update the text and the image when I click on It (for example).
My structure is like this:
$(".dropbtn, .burger").click(function() {
$(this).next(".dropdown-content, .items").stop().slideToggle(500);
//$(this).find(".arrow-up, .arrow-down").toggle();
});
// If you click outside dropdown - close dropdown
var $menu = $('.dropdown');
$(document).mouseup(function(e) {
if (!$menu.is(e.target) && $menu.has(e.target).length === 0) {
$('.dropdown-content').hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="javascript:void(0)" class="dropbtn">
<img src="assets/img/languages/flag_en.png" alt=""> EN
<span class="ico ico-pointer_down"></span>
</a>
<div class="dropdown-content" id="dd-content">
<img src="assets/img/languages/flag_br.png" alt=""> PT
<img src="assets/img/languages/flag_es.png" alt=""> ES
<img src="assets/img/languages/flag_fr.png" alt=""> FR
<img src="assets/img/languages/flag_de.png" alt=""> DE
<img src="assets/img/languages/flag_it.png" alt=""> IT
</div>
You could wrap the text in the span like :
<span class="lang">EN</span>
And attach click event then on click copy the text and image to the .dropbtn and hide the clicked anchor using hide class and finally remove the class hide from all the other anchors, like :
$(".dropbtn").click(function() {
$(this).next(".dropdown-content, .items").stop().slideToggle(500);
});
// If you click outside dropdown - close dropdown
var $menu = $('.dropdown');
$(document).mouseup(function(e) {
if (!$menu.is(e.target) && $menu.has(e.target).length === 0) {
$('.dropdown-content').hide();
}
});
$("#dd-content a").click(function() {
var text = $(this).text();
var img = $(this).find('img').clone(true);
$('.dropbtn .lang').text(text);
$('.dropbtn img').replaceWith(img);
$("#dd-content a").removeClass('hide');
$(this).addClass('hide');
});
a.hide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="javascript:void(0)" class="dropbtn">
<img src="assets/img/languages/flag_en.png" alt=""><span class="lang">EN</span>
<span class="ico ico-pointer_down"></span>
</a>
<div class="dropdown-content" id="dd-content">
<img src="assets/img/languages/flag_en.png" alt=""> EN
<img src="assets/img/languages/flag_br.png" alt=""> PT
<img src="assets/img/languages/flag_es.png" alt=""> ES
<img src="assets/img/languages/flag_fr.png" alt=""> FR
<img src="assets/img/languages/flag_de.png" alt=""> DE
<img src="assets/img/languages/flag_it.png" alt=""> IT
</div>
First of all you need a click event-handler for your images.
You are using a click event-handler already.
$(".dropdown-content img").click(function (e) {});
Inside your event-handler you need to define what to do.
Your mission is to change the src attribute.
So what you need to do first is to save the attribute in a variable.
var src = $(this).attr("src");
Then you need to change the attribute of the image you want to change.
$(".dropbtn").attr("src", src); //<-- the first parameter defines the attribute you want to change.
//The second attribute is our variable we set earlier.
In the end, it should look like this:
$(".dropdown-content img").click(function (e) {
var src = $(this).attr("src"); //<-- getting the attribute of the clicked element (this)
$(".dropbtn").attr("src", src); //<-- changing the attribute.
});
There are a lot of guides out there that can help you out.
However, this is not best practise for internalization but might be good to learn some basic JQuery and JS rules.
I would wrap the country name in a span. Then, when you click on the language options, swap out the image src and text for the chosen language.
I have added a little css to help illustrate the image src changing.
$(".dropbtn, .burger").click(function(e) {
e.preventDefault();
$(this).next(".dropdown-content, .items").stop().slideToggle(500);
//$(this).find(".arrow-up, .arrow-down").toggle();
});
// If you click outside dropdown - close dropdown
var $menu = $('.dropdown');
$(document).mouseup(function(e) {
if (!$menu.is(e.target) && $menu.has(e.target).length === 0) {
$('.dropdown-content').hide();
}
});
var $lang = $('.dropbtn');
//when user clicks on language
$('.dropdown-content').on('click', 'a', function(e) {
e.preventDefault();
var $this = $(this),
$img = $this.find('img');
//set the image of .dropbtn to the chosen image
$lang.find('img').attr('src', $img.attr('src'));
//set the name of the language
$lang.find('.lang-name').text($this.text());
});
<!-- added to help visualise the image src attribute changing. Can be safely ignored. -->
.dropbtn img:after {
content: attr(src);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#" class="dropbtn">
<img src="assets/img/languages/flag_en.png" alt=""> <span class="lang-name">EN</span>
<span class="ico ico-pointer_down"></span>
</a>
<div class="dropdown-content" id="dd-content">
<img src="assets/img/languages/flag_br.png" alt=""> PT
<img src="assets/img/languages/flag_es.png" alt=""> ES
<img src="assets/img/languages/flag_fr.png" alt=""> FR
<img src="assets/img/languages/flag_de.png" alt=""> DE
<img src="assets/img/languages/flag_it.png" alt=""> IT
</div>

jQuery find closest

I'm trying to get the a href of an list item.
HTML
<div class="popup" style="display: none;">
<div class="product">
<div class="photo">
<a href="" class="sendkleur" id="link69"> <!-- href im trying to reach -->
<img id="product-collection-image-69" src="" alt="Test kleur" class="popup-image69">
</a>
</div>
<a href="" class="sendkleur" id="link69">
<strong>Test kleur</strong>
</a>
<span class="swatchLabel-category">Kleur:</span>
<p class="float-clearer"></p>
<div class="swatch-category-container" style="clear:both;" id="ul-attribute137-69">
<img onclick="listSwitcher();" src="" id="a137-32" class="swatch-category" alt="Beige" width="12px" height="12px" title="Beige">
<img onclick="listSwitcher();" src="" id="a137-36" class="swatch-category" alt="Zwart" width="12px" height="12px" title="Zwart">
</div>
<p class="float-clearer"></p>
</div>
</div>
There are multiple popups on the site and thats what makes it difficult. At first I used this code
var link = jQuery('.photo').find('a')[0].getAttribute("href");
But this ofcourse only returns the href of the first popup. Then I tried this code:
var link = jQuery('.photo').closest('a').attr("href");
But this returned undefined
Then I tried this:
var link = jQuery(this).closest('a').attr("href");
But that also returns undefined
Edit
Here is the whole jQuery code snippet
jQuery(document).ready(function(){
jQuery('.swatch-category-container img').click(function(){
var kleur = jQuery(this).attr('title');
var link = jQuery('.photo').find('a').attr("href");
console.log(link);
link += "?kleur="+kleur;
console.log(link);
jQuery('.photo').find('.sendkleur').attr("href", link);
});
});
Working from the .swatch-category-container img element, you can traverse the DOM to find the required a like this:
$('.swatch-category-container img').click(function() {
var link = $(this).closest('.popup').find('.photo a').prop('href');
// do something with link here...
});
If this is the .swatch-category-container img element then, the anchor is the previous to previous sibling of the ancestor swatch-category-container element
var link = jQuery(this).closest('.swatch-category-container').prev().prev().attr("href");
Since you said multiple popups, the idea would be like this.
1. Get all popups
2. From each popup in all popups
Get the photo href item
$('.popup').each(function() {
var hrefItem = $(this).find('.photo a').attr('href');
//Do your processing with href item
});

jQuery finding closest image src to a div

if I have the following html:
<div class="showPin">
<div class="pinIt" style="display: none;">
<img src="images/pinbutton.jpg" class="pinbuttonImg">
</div>
<a href="myimage.jpg">
<img class="lazy data-lazy-ready" src="myimage.jpg" data-lazy-type="image" data-lazy-src="http://dev.papermusepress.com/stageblog/wp-content/uploads/2012/11/Fall_baby_shower_mantle2.jpg" alt="Fall Baby Shower Mantle" width="700" height="393" style="display: inline;">
</a>
</div>
how can i get my alert function to work so it alerts the img src that is the actual image getting pinned, which has a class="lazy" always in it.
$('div.pinIt').click(function() {
var url = $(this).closest('img.lazy').attr('src');
alert(url);
});
all it alerts for me is undefined. what am i doing wrong?
$('div.pinIt').click(function() {
var url = $(this).next('a').find('img.lazy').attr('src');
alert(url);
});
Closest traverses thru the ancestors.
But the image is inside the sibling(anchor tag) of the div. So try it this way..
If you want to use .closest() then this should work..
$('div.pinIt').click(function() {
var url = $(this).closest('.showPin').find('img.lazy').attr('src');
alert(url);
});
One of the easiest ways is to go up to parent and search for image element inside:
$("div.pinIt").click(function() {
var url = $(this).closest("div.showPin").find("img.lazy").attr("src");
alert(url);
});

Obtaining the ID of an IMG tag in jQuery

I have the following code (in this case for two images - but in reality, it could be replicated N times:
<figure title="" class="DragBox" dragableBox="true" style="opacity: 1;" id="thumb_1">
<span class="pic" id='UAJ754'>
<span class="imagewrap"> </span>
<span class="overlay">
Image Information
</span>
<img src="/pics/UAJ754.jpg" alt="">
</span>
<figcaption class="AlbumFig_Caption">A picture caption.
</figcaption>
</figure>
<figure title="" class="DragBox" dragableBox="true" style="opacity: 1;" id="thumb_2">
<span class="pic" id='JB6732'>
<span class="imagewrap"> </span>
<span class="overlay">
Image Information
</span>
<img src="/pics/JB6732.jpg" alt="">
</span>
<figcaption class="AlbumFig_Caption">A second picture caption.
</figcaption>
</figure>
Now the span which has the class of 'pic' has a jQuery mousedown event associated with it - so that it doesn't matter which image the mouse is clicked on, the pic tag will log the event and display a popup window with data. That all works fine.
But I need to obtain either the ID tag of the specific 'pic' that had the mouse down, or retrieve the src of the IMG so i can get the ID, as this needs to be passed to the popup window to display the correct info for the right picture.
I have the following JS code:
$(".pic").mousedown(function(e) {
var mouseX = e.pageX;
var mouseY = e.pageY;
if (e.which === 3) {
$('.infobox').css({'top':mouseY+'px','left':mouseX+'px'}).fadeIn();
var imgref = $(".pic").attr('id');
alert (imgref);
return false;
}else{
$('.info').fadeOut();
}
});
Again, this works fine, but it only gives me the ID of the first 'pic' span no matter which 'pic' span is clicked. How can I get the ID field of the current 'pic' span ... the one that the mouse was over when the use pressed the button??
try:
var imgref = $(this).attr('id');
or:
var imgref = $(this).prop('id');
instead of :
var imgref = $(".pic").attr('id');
$(".pic") will give the first div that have the class pic not the one you clicked on
var imgref =this.id;
because this is also an object and $(this) is wrapping an object in another object;
var imgref = $('img', this).attr('src');
you will get the src of the IMG.
Instead of using var imgref = $(".pic").attr('id');
Use this: var imgref = $(this).attr('id');

Rewriting HTML code using javascript

I have some markup here that I need to reformat using javascript. Basically, I have this code:
<div id="images">
<img src="01.jpg">
<img src="02.jpg">
<img src="03.jpg">
<img src="04.jpg">
<a id="src" href="01.jpg"></a>
<a id="src" href="02.jpg"></a>
<a id="src" href="03.jpg"></a>
<a id="src" href="04.jpg"></a>
</div>
and I want javascript to rewrite the code so that the images are placed inside the anchors. Like this:
<div id="images">
<a id="src" href="01.jpg"><img src="01.jpg"></a>
<a id="src" href="02.jpg"><img src="02.jpg"></a>
<a id="src" href="03.jpg"><img src="03.jpg"></a>
<a id="src" href="04.jpg"><img src="04.jpg"></a>
</div>
any ideas?
<script>
var div = window.document.getElementById("images");
var anchors = div.getElementsByTagName("A");
var imgs = div.getElementsByTagName("IMG");
for (var i = anchors.length - 1; i >= 0; i--) {
anchors[i].appendChild(imgs[i]);
}
</script>
General strategy:
Get a reference to the "images" div
Create a temporary object to store images, e.g. var imgs = {};
Loop over all img elements within the div. For each element:
Add each element to imgs, using its src as the key
Loop over all a elements within the div. For each element:
Lookup the image from imgs using the element's href attribute
Remove the img from its current location, and re-insert it within the body of the a.

Categories