Hi all,
I'm creating a simple gallery as a way to dip my toes into jQuery. I have thumbnails, each of which link to an image file, and when the user clicks on them the main image in the center is swapped. This works fine.
I'm now coding the "previous" and "next" buttons. They will work the same way -- they just link to a photo, and when clicked the main photo is swapped. However, the link needs to update whenever a new image is displayed.
The way I am doing this now is to: 1) Go through the list of thumbnails and work out which thumbnail in the list is the one that points to the current main image, 2) find the previous and next thumbnails (if they exist), 3) update the links and show the previous and next buttons as required.
The code below works fine, however I feel like I am doing it in an inefficient way:
- // set previous and next buttons to link to appr. photos in list
- function setPreviousAndNext(){
- var currentPhoto = $('#photo img').attr('src');
-
- var foundPrevious = false;
- var foundNext = false;
- var previous, next;
- $('.prev-next a').hide(); // hide prev and next, show only if necessary
-
- $('.thumb').each(function(){
- if ($(this).attr('href') == currentPhoto) {
- foundPrevious = true;
- // add border to thumb and caption to image
- $(this).parent().attr('style', 'border: 2px solid gray;');
- $('#caption').html($(this).children().attr('alt'))
- } else {
- if (!foundPrevious){
- previous = $(this);
- } else if (!foundNext){
- next = $(this);
- foundNext = true;
- }
- $(this).parent().attr('style', 'border: 2px solid white;');
- }
- });
- if (previous != null)
- $('#previous a').attr('href', previous.attr('href')).show();
- if (next != null)
- $('#next a').attr('href', next.attr('href')).show();
- }
Instead of having to store the previous and next image using flags and what-not, it would be much easier if I could say
- $('.thumb').each(function(){
- if ($(this).attr('href') == currentPhoto) {
- previous = $('.thumb').each().previous();
- next = $('.thumb').each().next()
- // add border to thumb and caption to image
- $(this).parent().attr('style', 'border: 2px solid gray;');
- $('#caption').html($(this).children().attr('alt'))
- } else {
- $(this).parent().attr('style', 'border: 2px solid white;');
- }
- });
... or something, where "previous()" and "next()" just peek at the previous and next items in the list.
Is there some efficient way of doing this? Or another way to make my code nicer?
Thanks!