0

I got the following code:

window.setInterval(function(){
    var id = $('.slidermenu.currentone').attr('data-id');
    var newid = parseInt(id) + 1;
    //alert(newid + ' - ' + id);

    $('.slidermenu.currentone').animate({backgroundColor: 'white'}, 'slow');
    $('.slidermenu.currentone').removeClass("currentone");
    $('slidermenu[date-id='+newid+']').animate({backgroundColor: '#f3f3f3'}, 'slow');
    $('slidermenu[date-id='+newid+']').addClass("currentone");
    $('#activeimage img.currentone').fadeOut('slow');
    $('#activeimage img.currentone').removeClass("currentone");
    $('#activeimage img[data-id='+newid+']').fadeIn('slow');
    $('#activeimage img[data-id='+newid+']').addClass("currentone");
}, 3000);

I'm trying to make a function which runs each 3 second, and then make my slider show the next image. well, it works pretty good first time it runs. But second time, it just doesn't work.

I think the problem might be with making the var newid have the number of from id, plus 1.

Also, I actually need it to do this up to number 5, and then after that goes down to number 1 again.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Mark Topper
  • 339
  • 1
  • 6
  • 14

3 Answers3

2

It looks like you are missing the . selector when setting the new slider menu to be the current one. Try this:

$('.slidermenu[date-id='+newid+']').animate({backgroundColor: '#f3f3f3'}, 'slow');
$('.slidermenu[date-id='+newid+']').addClass("currentone");
0

To increment the id, you need to make the id variable outside of the increment function and then increment it each time the interval function is being called. You can make it available from a closure and not have it global, which is usually preferred.

// make an anonymous function which reads the id attr and stores it in the id var.
var intervalFunction = (function(){
var id = $('.slidermenu.currentone').attr('data-id')
  , id = parseInt(id);

// return a function which will be run after every 3s and will increment the id
return function(){
  console.log(id++);
  // your slider code here
}})();

window.setInterval(intervalFunction, 1000);
GitaarLAB
  • 14,536
  • 11
  • 60
  • 80
gregor
  • 558
  • 4
  • 11
0

The problem is that each time your interval function runs, it's adding 1 to the value of data-id, which doesn't change. Since you want to loop through 5 values, you need to store your increment in a separate value, outside of the interval function -- using a closure in the following code:

window.setInterval(function() {
  var inc = 0;
  return function() {
    inc = 1 + inc % 5;
    var id = $('.slidermenu.currentone').attr('data-id');
    var newid = parseInt(id) + inc;
    alert(inc);
    // slider code
  }
}(), 3000);
mike
  • 7,137
  • 2
  • 23
  • 27