Skip to content Skip to sidebar Skip to footer

Jquery Within A Javascript For Loop Not Working

I've trying to run jQuery inside a for loop like this: var frameNumber = 15; // How many frames are in your animation for(var i = 1; i < frameNumber + 1; i++){ var flipDela

Solution 1:

You are misusing the delay() function. jQuery will only queue up effects out-of-the-box (e.g. fadeIn() or slideUp()), and not things like show(), hide(), or addClass().

Example of non-working delay() with addClass(): http://jsbin.com/hayay/4/

Instead, you should just use setTimeout like others have mentioned. I'd recommend a recursive approach, though, instead of a for loop:

var frameNumber = 15;
showFrame(1);
functionshowFrame(i) {
  $('.flipbook').addClass('flipbook-' + i);
  if (i < frameNumber) {
    setTimeout(function() { showFrame(i+1); }, 100);
  }
}

Solution 2:

Try this:

addClass('flipbook-' + (i<10?("0"+i):i));

This will add the missing zero for i<10. And about the delay - it would not work with addClass. You should stick with the setTimeout option.

Solution 3:

Fiddle Demo

var frameNumber = 15;
for (var i = 1; i < frameNumber + 1; i++) {
    (function (x) {
        setTimeout(function () {
            $('.flipbook').addClass('flipbook-' + x);
            console.log(x);
        }, x * 100)
    })(i)
}

Solution 4:

As has been said already, the addClass() method is an immediate method invocation. It does not, by default, go through the animation queue which is required in order to work with .delay().

Here's an interesting solution I came up with that allows you to make any jQuery method work via the animation queue and thus you can sequence methods via the built-in animation queue, can use .delay() to control timing, can intersperse with other animations, etc...

// generic method to allow you to run any jQuery method through the animation queue// so they will be serialized with other asynchronous animation methods// such as .delay(), .animate(), .slideUp(), etc...
jQuery.fn.queueMethod = function(methodName /* arg1, arg2, ... */) {
    var self = this;
    var args = Array.prototype.slice.call(arguments, 1);
    self.queue(function(next) {
        self[methodName].apply(self, args);
        next();
    })
    returnthis;
}    

var frameNumber = 15; // How many frames are in your animationfor (var i = 1; i <= frameNumber; i++) {
    $('.flipbook').delay(100).queueMethod("addClass", "flipbook-" + i);
}

This will run each addClass method, 100ms apart.

Several working examples of slightly different ways of doing it: http://jsfiddle.net/jfriend00/38BbM/

Post a Comment for "Jquery Within A Javascript For Loop Not Working"