Reputation: 167
I have a question about streamlining my jquery code. I have a list of images and each has a unique id and the click event displays the larger image and its info. Is there a way to do this with a loop similar to php's foreach loop?
$(function() {
$('img#cl_1').click(function() {
$('div#left').html('display image').slideDown('fast');
$('div#right').html('display image info').slideDown('fast');
});
$('img#cl_2').click(function() {
$('div#left').html('display image').slideDown('fast');
$('div#right').html('display image info').slideDown('fast');
});
$('img#cl_3').click(function() {
$('div#left').html('display image').slideDown('fast');
$('div#right').html('display image info').slideDown('fast');
});
$('img#cl_4').click(function() {
$('div#left').html('display image').slideDown('fast');
$('div#right').html('display image info').slideDown('fast');
});
/*so on and so forth*/
});
Upvotes: 4
Views: 416
Reputation: 1976
If you don't want to use a class selector, you can also use something like this:
$(function() {
$('img[id^="cl_"]').click(function() {
$('div#left').html('display image').slideDown('fast');
$('div#right').html('display image info').slideDown('fast');
});
});
This should work on any image with an element id that starts with 'cl_'. A class selector is definitely cleaner though.
Upvotes: 3
Reputation: 13386
If 'display image' and 'display image info' are different values for each image, consider loading them in an array or getting them via AJAX. Then alter your event binding to look like this:
$('img.showStuff').click(showDetails);
function showDetails() {
var id = this.id;
$('div#left').html(images[id]).slideDown('fast');
$('div#right').html(info[id]).slideDown('fast');
}
Upvotes: 2