beetroot
beetroot

Reputation: 13

Iterate over specific CSS-id's with jQuery

I'm making an image gallery in which I want the user to be able to click on a thumbnail and get a bigger image displayed.

This is the php-code to iterate over all images in a directory on the server and display them and give them each a unique id.

echo '<div id="image' . $i . '" class="image">' . $thumbsrc . '</div>';

echo '<div id="bigimage' . $i . '" class="bigimage">' . $imagesrc . '</div>';

This works fine, I use

$(".bigimage").hide();

to hide the bigger images.

So what I could do now is this:

$("#image1").click(function() {
$("#bigimage1").show();
});

$("#bigimage1").click(function() {
$("#bigimage1").hide();
});

But I find for up to 30 pictures I can't write 30 instances of this so I wanted to loop it.

I tried

for (var i = 1; i < 30; i++) {
    $('#image' + i).click(function() {
        $('#bigimage' + i).show();
    });
    $('#bigimage' + i).click(function() {
         $('#bigimage' + i).hide();
    });
}

Which doesn't seem to work? Why not?

If I do

for (var i = 1; i < 10; i++) {
    $('#image' + i).append('<p>test' + i + '</p>');
}

it appends paragraph's to every #image-element so looping selector's seem to work.

How would I do this?

Thanks beforehand.

Upvotes: 1

Views: 141

Answers (1)

Ram
Ram

Reputation: 144689

That's because all of your click handlers use the same value, for understanding what happens, you can refer to this question: Javascript infamous Loop issue?

Since your elements have classes, you can use you classes instead. index method returns the index of the passed element in a collection. After getting the index, for selecting the corresponding element in another collection you can use the eq method.

var $img = $('.image');
var $bigImg = $('.bigimage').hide();

$img.on('click', function() {
   var i = $img.index(this);
   $bigImg.eq(i).show();
});

$bigImg.on('click', function() {
   // this keyword refers to the clicked element
   $(this).hide();
});

Upvotes: 1

Related Questions