user1563944
user1563944

Reputation: 403

Selecting next and previous list items

I am working on a simple image gallery with a larger picture displayed above a line of thumbnails below. I have set the initial opacity of each thumbnail to 0.3 by using a css rule targeting the li. Using javascript I want to change the opacity of the thumbnail that is currently selected to 1, but keep the rest set at 0.3.

I have managed to change the current thumbnail's opacity from 0.3 to 1 but what I cannot figure out how to do is change the previous (or next) thumbnails opacity back to 0.3.

For example, if thumbnail #3 is currently selected I want all the remaining 5 thumbnails to revert back to their orignal opacity setting of 0.3

I have put some of my code into the below link so you can get an idea of what I going on about.

div class="thumbnails">

<ul>
    <li><a href='#' class='thumb' id="thumb_1"></a></li>
    <!-- MORE FOLLOW -->
</ul>

$("#nextBtn").click(function() {
    currentPic++;
    $(".thumbnails ul li:nth-child(" + currentPic + ")").animate({
        "opacity": "1"
    });
});

Full code sample: http://jsfiddle.net/nqKJw/

Upvotes: 0

Views: 131

Answers (3)

unloco
unloco

Reputation: 7330

Here's a nice solution using the .current class

CSS:

.current{ opacity:1 !important; }

Jquery:

$("#nextBtn").click(function() {
    var nextThumb = $('.thumbnails .current').removeClass('current').next();
    nextThumb = nextThumb.length?nextThumb:$('.thumbnails li:first');
    $(nextThumb).addClass('current');
});

$("#prevBtn").click(function() {
    var nextThumb = $('.thumbnails .current').removeClass('current').prev();
    nextThumb = nextThumb.length?nextThumb:$('.thumbnails li:last');
    $(nextThumb).addClass('current');
});​

Upvotes: 0

ChrisHarris2012
ChrisHarris2012

Reputation: 404

Simply change the opacity value of the current item before changing the current item

$("#nextBtn").click(function() {
  $(".thumbnails ul li:nth-child(" + currentPic + ")").animate({
      "opacity": ".3"
  });

  currentPic++;

  $(".thumbnails ul li:nth-child(" + currentPic + ")").animate({
      "opacity": "1"
  });
});

And similarly for prevBtn

Updated JSFiddle

Upvotes: 0

Chris Baker
Chris Baker

Reputation: 50612

In the function where you are setting the opacity of the desired thumbnail to 1, first set all thumbnails to an opacity of .3:

$("#nextBtn").click(function() {
    $(".thumbnails ul li").animate({
        "opacity": "0.3"
    });
    currentPic++;
    $(".thumbnails ul li:nth-child(" + currentPic + ")").animate({
        "opacity": "1"
    });
});

Try it: http://jsfiddle.net/nqKJw/1/

Upvotes: 1

Related Questions