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*/
});
If you don’t want to use a class selector, you can also use something like this:
This should work on any image with an element id that starts with ‘cl_’.
A class selector is definitely cleaner though.