AndyWarren
AndyWarren

Reputation: 2012

Get image src then apply it as href in .each loop

I have a content rotator built with jQuery Cycle and am trying to add jQuery Fancybox to it.

HTML:

<div class="secRotatorSlide">
    <a href="" class="iframe enlargePic">Enlarge</a>
    <img class="slideImg" src="secRotatorImg/slide1.png" alt="Slide 1" />
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>

There are multiple sets of the above HTML. All are rotating correctly.

jQuery:

jQuery('.secRotatorSlide').find('.slideImg').each(function() {
    var iframeSrc = jQuery(this)[0].src;
    //alert(iframeSrc)
    jQuery('a.enlargePic').attr('href', iframeSrc);    
});

If I comment out the line that sets the href, and uncomment the alert line it will alert every src correctly one after the other. If I leave it like it is, it gets the image src from the very last set of html and applies it to every href for all in all the sets of html.

What am I doing wrong? I presume it is in the last line of jQuery, but I am not sure. I've tried using this in that last line, but that does nothing at all.

Upvotes: 0

Views: 132

Answers (2)

Venkata Krishna
Venkata Krishna

Reputation: 15112

jQuery(this).prev('a.enlargePic').attr('href', iframeSrc);

The selector a.enlargePic selects all the links in the DOM with the specific class. Target the only which is next to your current image by using .prev()

Upvotes: 1

DRobinson
DRobinson

Reputation: 4471

Your selector, jQuery('a.enlargePic') is too generic. This will find all matching elements in the DOM, which you're proceeding to set href values for. You need to limit its scope.

Try: jQuery(this).siblings('a.enlargePic').attr('href', iframeSrc);

That way you only set the value for the elements which are children of the same parent (siblings) of the element that you're dealing with.

http://api.jquery.com/siblings/

EDIT: And if all of your images and anchors share the same parent, then consider $.prev()

Upvotes: 4

Related Questions