Grow your CSS skills. Land your dream job.

Jquery looping

  • # November 14, 2010 at 4:33 pm

    Hi folks,

    I am looking to build a kind of news ticker. Effectively I have a p tag and a ul. Id like to loop through the ul and post each li to the p in turn.

    Currently I’m using .each to loop through the li elements. This is working fine but it all happens almost instantly as you would expect.

    What ID really like to do is to add a pause. Any idea how to add that pause?

    I have tried .delay and setting opacity over 1000 ms. The usual tricks.
    These don’t work because they are outside of the loop.

    Any ideas would be fantastic

    # November 14, 2010 at 7:15 pm

    Edit: Updated jsFiddle example to be more clear and functional.

    This can be done with the setInterval function native to JavaScript using a ‘global’ counter.

    I created a fairly raw example here at jsFiddle: http://jsfiddle.net/F3eaW/3/

    So as you’ll see in the code, the key components are the setInterval and the addItem function.

    var tick = setInterval(function() {
    addItem()
    }, 2000);

    There’s some comments, but I’ll explain this a bit better in case you’re new to javascript. So what this will do is set an interval timer as soon as the script loads that will call the addItem function every 2 seconds, or however long you choose based on the second parameter. The addItem function will then count up the global counter variable (“i” in my example) and use that to set the text of <p> to the list item in the array corresponding to that counter number (starting at 0 of course).

    Being that setInterval will keep running until you kill it, counting up that counter variable will effectively loop through the array in a timed fashion.

    Lastly, in case you’re wondering, I set the interval to a variable so you can kill it if you want later on like this:
    clearInterval(tick);

    As I said it’s a pretty basic example, but that should be able to set you on your way.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".