Reputation:
When I click a button, I want to apply some jQuery (let's say fadeOut) to the first image with the class my-image.
When I click that button again, I want to do the same thing to the next occurrence in the markup of an image with the class my-image.
The images all appear in various places throughout the markup and are not necessarily siblings.
Thanks for any help.
Upvotes: 1
Views: 485
Reputation: 1018
Though untested, you could take advantage of the visible and first psuedo-selectors.
$('#mybutton').click(function(){
$('.my-image:visible:first').fadeOut();
}
If your function is one that animates use not and animated to ensure you don't match one currently fading:
$('#mybutton').click(function(){
$('.my-image:visible:not(:animated):first').fadeOut();
})
To refine our understanding of the filter method, I just tested long hand as well.
$('#mybutton').click(function(){
$('.my-image')
.filter(':visible')
.not(':animated')
.filter(':first')
.fadeOut();
})
This is particularly useful during development to quickly comment out various steps:
$('#mybutton').click(function(){
$('.my-image')
.filter(':visible')
// .not(':animated')
.filter(':first')
.fadeOut();
})
Upvotes: 7
Reputation: 54056
You can have two classes. One for the images that were already faded out, and another for those who were not. Like:
<img src="" alt="" class="not_faded" />
and
<img src="" alt="" class="faded" />
Now with jQuery you can do the following:
$('#mybutton').click (function (){
$('.not_faded:first').fadeOut (); // your fade out effect
$('.not_faded:first').attr ('class', 'faded');
});
This code gets the first image that belongs the not_faded class and makes the fade out effect. Then changes the class of that image to 'faded'. So the first image of the class not_faded, next time, will be the second one.
Edit: check out Matt's solution, it's more elegant and takes full advantage of jQuery.
Upvotes: 1