tags:

views:

156

answers:

3

Is it possible to change an items class or ID based on some type of timer? Every 1500ms it would go to hey-there-1, then 1500ms later hey-there-2.. etc.. something that I could possibly control how many intervals it goes through..

  • hey-there
  • hey-there-1
  • hey-there-2
  • hey-there-3
  • (back to beginning) hey-there
  • etc

Thanks

A: 

See:

setTiemOut
setInternal

var pp = 0;

jQuery("#id").html(jQuery("#id").html() + "<div>hey there"+(pp++)+"</div>");
andres descalzo
A: 

I would suggest against changing the ID of the element - instead go for "frame1/frame2/frame3" classes.

$(function() {
  var $target = $("#hey-there");
  var classes = ['frame0', 'frame1', 'frame2', 'frame3'];
  var current = 0;

  setInterval(function() {
    $target.removeClass(classes[current]);
    current = (current+1)%classes.length;
    $target.addClass(classes[current]);
  }, 1500); // 1500 ms loop
});
gnarf
+1  A: 

A plugin function as such will allow you to do what you want:

jQuery.fn.rotateClasses = function(classes, interval, max) {
    var currentRotation = 0;
    var timer = null;

    var rotateFn = (function() {
            var currentClass = currentRotation % classes.length;

     var previousClass = currentClass - 1;
     if(previousClass == -1) previousClass = classes.length - 1;

     this.addClass(classes[currentClass]).removeClass(classes[previousClass]);

     currentRotation += 1;

            if(max > 0 && currentRotation >= max) clearInterval(timer);
    })();

    timer = setInterval(rotateFn, interval);

    return this;
};

Then you can simply call it using the following:

$('#mydiv').rotateClasses(["class1", "class2", "class3"], 1000, 20);

Simply modify the parameters as you wish. First parameter is an array of classes to rotate, second is the interval to rotate them to, and the third is the maximum number of iterations. If set to 0, it iterates ad-infinitum.

Andrew Moore