supersize
supersize

Reputation: 14783

next() and prev() with find

I have a markup which is the following:

<div>
  <a href="img1.jpg">
    <img src="img1.jpg"/>
  </a>
  <a href="img2.jpg">
    <img style="display: none" src="img2.jpg"/>
  </a>
  <a href="img3.jpg">
    <img style="display: none" src="img3.jpg"/>
  </a>
  <a href="img4.jpg">
    <img style="display: none" src="img4.jpg"/>
  </a>
  <a href="img5.jpg">
    <img style="display: none" src="img5.jpg"/>
  </a>
  <a href="img6.jpg">
    <img style="display: none" src="img6.jpg"/>
  </a>
</div>

as you can see the first image inside the first <a> is shown. I would like to trigger a function that the next <img> gets shown and the first invisible.

var visible = $('img:visible');
$('#trigger').click(function() {
   visible.next('a').find('img').fadeIn();
   visible.fadeOut();
});

how do I have to handle .find() and next() that it will work?

Upvotes: 1

Views: 51

Answers (4)

Jai
Jai

Reputation: 74738

update this:

var visible = $('img:visible');

to this:

var visible = $('img:visible').closest('a');

Because with your existing selector visible is trying to find another anchor next to itself, which is not there so that won't work instead you can update your var visible to the traverse up to the closest parent, which is anchor an a.

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82241

You are targeting the visible image element.as a is not the sibling of image, visible.next('a') will return undefined. You need to traverse to parent anchor(using .closest('a') or .parent()) and then use .next().Try this:

 visible.closest('a').next().find('img').fadeIn();

Upvotes: 2

Adil Shaikh
Adil Shaikh

Reputation: 44740

Try this -

visible.closest('a').next('a').find('img').fadeIn();

Upvotes: 1

Felix
Felix

Reputation: 38102

You need to use:

visible.parent().next('a').find('img').fadeIn();

since you want to get the next immediate sibling of parent anchor of visible image instead

Upvotes: 2

Related Questions