I’m trying to paginate an image gallery using jquery. The image directory I’m using contains about 600 images, named like this: “photo1.jpg” … “photo(n).jpg” … “photo600.jpg”.
Suppose I have a variable holding the page number var page and there are 40 images on each virtual page. I want to do something like:
for (var i = 0; i<40; i++){
var imageNum = (((page*40)-40)+i+1);
$("img")[i].attr("src","photo"+ imageNum + ".jpg"); // Doesn't work
}
}
This is hackish but do you see what I am trying to do? The jquery API had some info on using each() to iterate through a jquery object but i couldn’t figure out how to send the each function a parameter holding data about which page I am on, which I will need to determine the paths to the images. I’m going for something like:
$("img").each(function (i) {
//code to update image paths based on page parameter
});
I’m open to different approaches as well, I am a total noob and I feel like I might be going about this in the wrong way to begin with :S.
Edit
Thanks to everyone for their answers.
If you are looking for a quick and simple answer that works using each(), check out Jeff B’s answer.
I accepted patrick dw’s answer because it goes into a bit more detail about a separate mistake I was making and covers another approach as well. Also, please see our comments on his response if you are like me and thought you needed to pass parameters to .each().
This doesn’t work because
[i]gives you a native DOM element that is not wrapped in a jQuery object.jQuery has the
eq()[docs] method to give you the element wrapped so you can call theattr()[docs] method.As an alternative, you can pass a function directly to the
attr()[docs] method that will loop over the elements for you.The
returnvalue is the value that will be assigned to the attribute you’re setting (which issrcin this case).