TheDeceived
TheDeceived

Reputation: 5

jQuery - Loop through images and hide all but clicked image

Here's my HTML for my images:

<img id="polaroid1" class="polaroid" onclick="fadeImages(this)" src="images/polaroid1.png">
<img id="polaroid2" class="polaroid" onclick="fadeImages(this)" src="images/polaroid2.png">
<img id="polaroid3" class="polaroid" onclick="fadeImages(this)" src="images/polaroid3.png">

After the user clicks any of these images, it calls the fadeImages() function. Here's my JavaScript and jQuery:

function fadeImages(e) {
    var clickedImage = $(e).attr('id');

    $('img').each(function() {
        if($(this).attr('id') != clickedImage) {
            $('img').animate({opacity: 0}, 500);
        }
    });
 }

Basically, I want all images BUT the clicked image to fade out, but I don't know how to pass the clicked image ID into the 'each()' function. Any ideas?

Upvotes: 0

Views: 727

Answers (2)

MushinNoShin
MushinNoShin

Reputation: 4886

Bind a click event on each image which fades all of it's sibling elements.

$('img.polaroid').on('click', function(event) {
  $(this).siblings('.polaroid').animate({opacity: 0}, 500);
});

Upvotes: 2

Reigel Gallarde
Reigel Gallarde

Reputation: 65254

function fadeImages(e) {
    $('.polaroid').not(e).animate({opacity: 0}, 500);    
}

a nicer way is to remove onclick on your images and use the power of jQuery...

Like this...

$(function(){
    var $imgs = $('.polaroid');
    $imgs.click(function(){
         $imgs.not(this).animate({opacity: 0}, 500);
    });
})

Upvotes: 1

Related Questions