Carter
Carter

Reputation: 1

Tricky Highlight Rotation JQuery - Timer and Selector

So this has been a fun project. I have 4 thumbnail images displayed on a page. Every couple seconds one of these thumbnails should be highlighted. (The highlight means a new image with a greybackground is made visible over the normal thumb) Upon mouse hover, I need to suspend the timer. I know I am close! Upon page load the first image does get its auto highlight, but the other images never get the auto highlight. Here is the JS:

    $(function() { // Shorthand for $(document).ready(function() {
        function nextImage() {
        var next = $('div.activeThumb.currentHighlight').
              removeClass('currentHighlight'). // Unhighlight old one
              next('div.activeThumb'); // Find next one
        if (next.length == 0) { // Cycle back to the first
              next = $('div.activeThumb:first');                  
        } 
        next.addClass('currentHighlight'); // Highlight new one                     
   }
   var timer = null;
   $('a.aThumb').hover(function() {
        clearInterval(timer); // Stop on hover
        $('div.activeThumb.currentHighlight').
              removeClass('currentHighlight');//Remove whatever the current auto                highlight is. :)
  }, function() {
        setInterval(nextImage, 2000); //Restart on exit 
  });
  nextImage(); // Highlight first image 
  setInterval(nextImage, 2000); // Start cycle
  });

You can check out the test page with the html and css if you would like. It is a little weird for a set up. http://cartercallahan.com/TestSite/javaSlider2/

Upvotes: 0

Views: 281

Answers (1)

lucuma
lucuma

Reputation: 18339

The next method is not as you expected. I have an index based approach that should work fine for you. The jsfiddle example: http://jsfiddle.net/lucuma/pm6fA/5/

You can set an index and increment that index as you move through your array of thumbnails.

var activeClass = 'currentHighlight';
var timer;
var $thumbs;
var index = 0;

function nextImage() {   
      $thumbs.eq(index).removeClass(activeClass);
      index = (index+1) % $thumbs.length;
      $thumbs.eq(index).addClass(activeClass);      
  }

$(function() { 

    $('a.aThumb').hover(function() {
        clearInterval(timer); // Stop on hover
        $('div.activeThumb.currentHighlight').
            removeClass('currentHighlight');
  }, function() {
        timer = setInterval("nextImage()", 2000); //Restart on exit 
  });


    $thumbs = $('div.activeThumb');
    $thumbs.eq(index).addClass('currentHighlight');
    timer= setInterval("nextImage()", 2000); // Start cycle

});​

Upvotes: 1

Related Questions