jQuery finding closest image src to a div - javascript

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);
});

Related

How to handle: When image is clicked identical image generated using Javascript

The code below works to make one copy of the image clicked. I am needing the code below to work for multiple images.
For example if I click 5 images on the screen, the same 5 images should generate at the bottom of the page. The user should be able to select 5 out of 10 images. Any thoughts? Thanks!
JS:
function changeImage() {
var imgSrc = 'http://placehold.it/150';
if (document.getElementById('myImage').src === imgSrc) {
document.getElementById('new').src = imgSrc;
}
}
HTML
<a href="#" onClick="changeImage()">
<img id="myImage" src="http://placehold.it/150"></a>
<img id="new" src="http://placehold.it/200">
You can use JQuery clone() function
$('img').click(function() {
$('body').append($(this).clone());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="http://placehold.it/50x50">
<img src="http://placehold.it/50x50/000000/ffffff">
<img src="http://placehold.it/50x50/1C90F3/ffffff">
<img src="http://placehold.it/50x50/F2BB7C/ffffff">
you can use jquery to do that
HTML
<a href="#" id="my-image">
<img id="myImage" src="http://placehold.it/150"></a>
<img id="new" src="http://placehold.it/200" />
JS
$('#my-image').click(function(){
//setting attribute src to be equal as src from #myImage
$('#new').attr('src', $('#myImage').attr('src'));
//returning false in order to avoid default action
return false;
});
So that is it :)
Just remember to put this code after your html or into
$(document).ready(function(){ ..... });
I hope this helps.

jQuery append an img to every div

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.
}

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
});

If href equals id of another div do function

I have a hidden div with the details of a thumbnail that is visible on the page. When you click on the thumbnail, it should fadein or slideup the div with details.
I have set with jquery incremented ID's to each ".portfolio-item-details" to identify each one and then have set with jquery the same ID's to the href of the thumbnail.
<section id="portfolio1" class="portfolio-item-details hidden">content</section>
<a class="open-portfolio-item-details" href="#portfolio1" title="">
<img src="thumbnail.jpg">
</a>
<section id="portfolio2" class="portfolio-item-details hidden">content</section>
<a class="open-portfolio-item-details" href="#portfolio2" title="">
<img src="thumbnail.jpg">
</a>
Since this is done dynamically, how can I with jquery fadeIn or slideUp the ".portfolio-item-details" if the href is equal to the ID. Basically thumbnail with "#portfolio1" should slide up the div with "#portfolio1" on click.
This is my jquery code which to add the IDs and HREF is working perfectly but not working to slideUp or fadeIn the div with the same ID.
$(document).ready(function () {
var i=0;
$(".portfolio-item-details").each(function(){
i++;
var newID="portfolio"+i;
$(this).attr("id",newID);
$(this).val(i);
});
var i=0;
$(".open-portfolio-item-details").each(function(){
i++;
var newReadMoreHREF="#portfolio"+i;
$(this).attr("href",newReadMoreHREF);
$(this).val(i);
if ($(".portfolio-item-details").attr("id") == "newReadMoreHREF") {
$(this).fadeIn();
}
});
});
SOLUTION
Thanks to Austin's code, I was able to modify it to work with mine.
Check here: http://jsfiddle.net/jdoimeadios23/xpsrLyLz/
You want something like this?
HTML
<div class="image" value="1">
<img src="thumbnail.jpg" />
</div>
<div id="portfolio1" class="details">details</div>
<div class="image" value="2">
<img src="thumbnail.jpg" />
</div>
<div id="portfolio2" class="details">more details</div>
JS
$(document).ready(function () {
$('.details').fadeOut(1);
$(".image").click(function () {
var num = $(this).attr("value");
$("#portfolio"+num).fadeIn(1000);
});
});
JSFiddle Demo
You don't even need to bother with ID's so long as the next div below each image is it's details.
The problem is in this block
if ($(".portfolio-item-details").attr("id") == "newReadMoreHREF") {
$(this).fadeIn();
}
Because you're having two errors, the first one is that newReadMoreHREF is a variable, not a string in your HTML or a value to any variable and so on.
Second thing is, that in the variable declaration you're using "#portfolio"+i;, which would be good if you were about to select an element. But using it in the jQuery iif statement with .attr('id') will again cause a havoc.
The thing that you need is something like this
$(".open-portfolio-item-details").each(function(){
i++;
var newReadMoreHREF="portfolio"+i; // removed #
$(this).attr("href",newReadMoreHREF);
$(this).val(i);
if ($(".portfolio-item-details a").attr("id") == newReadMoreHREF) {
// you need to access the hyperlink in the element, not
// the element itself. this portfolio1 ID is of a hyperlink
// again here, this is referencing the main iterator.
$(this).fadeIn();
// are you sure you want to fade the .open-portfolio-item-details?
}
});
Removed the hash sign and then called the variable value to check against. It would execute to be true if the condition is true.
Try this:
HTML:
content
<section id="portfolio2" class="portfolio-item-details hidden">content</section>
<a class="open-portfolio-item-details" href="#portfolio2" title="">
<img src="thumbnail.jpg">
</a>
<div id="portfolio1" class="portfolio" hidden>Portfolio 1</div>
<div id="portfolio2" class="portfolio" hidden>Portfolio 2</div>
Jquery:
$('a.open-portfolio-item-details').on('click', function (e) {
e.preventDefault();
var id = $(this).attr('href');
$('.portfolio').hide();
$('.portfolio' + id).fadeIn();
});
Couldn't get the fiddle link for some reason.
Edit:
I don't know the name of the class that shows the content you want displayed, so as an example I'm using portfolio. Try putting this code into a fiddle

add content through javascript

I am trying to create a page where when you click on any of the three images. It inserts the content into the empty div above the image links.
Here is my javascript code:
<script type="text/javascript" src="js/jquery-1.8.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('img').click (function() {
$('.deal_content').append(<img src="deal_content.fw.png" width="587" height="299" alt="Your Deals!" />);
return false;
});
});
</script>
and this is the HTML it is to effect:
<div class="deal_content">
</div>
<div id="imagelink">
<a href="#">
<img src="for_men_btn.fw.png" width="200" height="87" alt="For Men" />
</a>
<a href="#">
<img src="for_couples_btn.fw.png" width="200" height="87" alt="For Couples" />
</a>
<a href="#">
<img src="for_teens_btn.fw.png" width="200" height="87" alt="For Teens" />
</a>
</div>
I wish the new image to be put in the deal_content class div.
In your append method, if you put double quotes around the HTML and replace the current quotes with single quotes, it should work. Append takes a string or a JQuery selector, not markup.
You need to make the element a string in order to pass it through append
$(document).ready(function() {
$('img').click (function() {
$('.deal_content').append('<img src="deal_content.fw.png" width="587" height="299" alt="Your Deals!" />');
return false;
});
});
Considerting this is what you want:
I wish the new iamge to be put in the deal_content class div.
You are almost there:
In the Javascript that you have:
$(document).ready(function () {
$('img').click(function () {
$('.deal_content').append();
return false;
});
});
you need a html() instead of append(). And insert a img tag, and grab the srcfrom the image thatw as clicked on.
$('.deal_content').html("Image \"" + $(this).attr("src") +"\" here: <img src=" + $(this).attr("src") + "/>");
See http://jsfiddle.net/nivas/PA63e/
$('#imagelink').on('click', 'img', function(){
$('.deal_content').append( this );
});
or if you want to duplicate the image:
$('#imagelink').on('click', 'img', function(){
$('.deal_content').append( this.cloneNode() );
});
is that what you want? This way it will only move the images that are inside imagelink element

Categories