29031

jQuery within a JavaScript for loop not working

Question:

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 flipDelay = i * 100; $('.flipbook').delay(flipDelay).addClass('flipbook-' + i); }

I'm trying to get the equivalent of this but with more flexibility so I can change how many frames I use:

$(function(){ setTimeout(function(){ $(".flipbook").addClass("flipbook-1") }, 100 ); setTimeout(function(){ $(".flipbook").addClass("flipbook-2") }, 200 ); setTimeout(function(){ $(".flipbook").addClass("flipbook-3") }, 300 ); setTimeout(function(){ $(".flipbook").addClass("flipbook-4") }, 400 ); setTimeout(function(){ $(".flipbook").addClass("flipbook-5") }, 500 ); setTimeout(function(){ $(".flipbook").addClass("flipbook-6") }, 600 ); setTimeout(function(){ $(".flipbook").addClass("flipbook-7") }, 700 ); setTimeout(function(){ $(".flipbook").addClass("flipbook-8") }, 800 ); setTimeout(function(){ $(".flipbook").addClass("flipbook-9") }, 900 ); setTimeout(function(){ $(".flipbook").addClass("flipbook-10") }, 1000 ); setTimeout(function(){ $(".flipbook").addClass("flipbook-11") }, 1100 ); setTimeout(function(){ $(".flipbook").addClass("flipbook-12") }, 1200 ); setTimeout(function(){ $(".flipbook").addClass("flipbook-13") }, 1300 ); setTimeout(function(){ $(".flipbook").addClass("flipbook-14") }, 1400 ); setTimeout(function(){ $(".flipbook").addClass("flipbook-15") }, 1500 ); });

The classes are defined in a CSS stylesheet and each class has a different background applied to it. I just need jQuery/JS to loop through them until the last frame is reached.

EDIT: It's not the flipbook-01 vs flipbook-1 that's preventing me from getting this to work. Sorry about that confusion.

EDIT: I need my div to look like this after the function has ran:

<div class="flipbook flipbook-1 flipbook-2 flipbook-3 flipbook-4 ... flipbook-15"></div>

Answer1:

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(): <a href="http://jsbin.com/hayay/4/" rel="nofollow">http://jsbin.com/hayay/4/</a>

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); function showFrame(i) { $('.flipbook').addClass('flipbook-' + i); if (i < frameNumber) { setTimeout(function() { showFrame(i+1); }, 100); } }

Answer2:

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.

Answer3:

<kbd><a href="http://jsfiddle.net/cse_tushar/daD6D/" rel="nofollow"><strong>Fiddle Demo</strong></a></kbd>

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) }

Answer4:

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(); }) return this; } var frameNumber = 15; // How many frames are in your animation for (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: <a href="http://jsfiddle.net/jfriend00/38BbM/" rel="nofollow">http://jsfiddle.net/jfriend00/38BbM/</a>

Recommend

  • MD5 Inconsistent between C# and golang
  • How do I get the handle to a comment element in javascript?
  • org.specs2.mock.Mockito matchers are not working as expected
  • Is SPLFileObject atomic?
  • Nunmpy sum() function + comprehensions: int32 or in64?
  • How to check if one div overlapped another during transition from one position to another
  • When is InputStream.available() useful?
  • Dropping support for JRE 1.3
  • regex: Match at least two search terms
  • Domain name setup with AWS S3 bucket with static hosting
  • CSS transition glitch
  • How is user.dir configured for Tomcat servlets?
  • Errno 2 using python shutil.py No such file or directory for file destination
  • How to import Navit into Eclipse and use it in own android project
  • Error “Reflect.defineMetadata” while trying to load a transient web worker
  • Spring Integration Bridge with poller not working as expected for JMS
  • Can long-polling be achieved in Restlet by just making the thread sleep?
  • What is the default HTTP verb in WebApi ? GET or POST?
  • Swift Initialization Rule Confusion
  • ckeditor and jquery UI dialog not working
  • How to make Twilio api Post request with the help of AFNetworking?
  • wxPython: displaying multiple widgets in same frame
  • FileReader+canvas image loading problem
  • R - Combining Columns to String Based on Logical Match
  • Change JButton Shape while respecting Look And Feel
  • Insert into database using onclick function
  • Deselecting radio buttons while keeping the View Model in synch
  • Fetching methods from BroadcastReceiver to update UI
  • Why HTML5 Canvas with a larger size stretch a drawn line?
  • Menu Color Fade on Hover with Jquery
  • Symfony2: How to get request parameter
  • GridView Sorting works once only
  • Use group_by to filter specific cases while keeping NAs
  • WPF Applying a trigger on binding failure
  • embed rChart in Markdown
  • Observable and ngFor in Angular 2
  • How to Embed XSL into XML
  • UserPrincipal.Current returns apppool on IIS
  • Unable to use reactive element in my shiny app
  • Conditional In-Line CSS for IE and Others?