tags:

views:

89

answers:

2

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.

+6  A: 

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();
})
Matt Gardner
..and thanks for the question, I've never previously tried to nest psudeos that deep.
Matt Gardner
+1 great complete answer.
bigmattyh
+1  A: 

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.

rogeriopvl
+1 although I would use addClass() and removeClass() instead of attr() in case some other class has already been applied to the image.
DrJokepu
OK, but once I've cycled through all of the images, they've all been set to "faded" so the code no longer does anything, because there are no more "not_faded" elements. I believe this would be the case for both your and Matt's suggestions. Any ideas for getting around that? I should probably mention that this is for one of those Coda slider showcases. I have the sliding working, but I want to add a bit more animation to the image that's currently being viewed.