Mobilpadde
Mobilpadde

Reputation: 1881

Show values from array in jquery

Ok, the title might make it sound easy (and maybe it is), but I can't figure out how to show values from an array, not just do a each with them, but put them on the site slowly, with a nice effect...

Like this Twitter widget, but from an array (maybe wait 2sec, and when throw another value from the array)?

My array contains another array, with 4 values, is it possible to show the first 2 values, wait about 2 sec, and then show the last 2 values? Now when the last two values is out (from the prev array), wait 2 more seconds, and show the next array (again with four values, first show 2, wait 2 sec, and show the next 2, and so on...)

Upvotes: 0

Views: 782

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074168

You can do this easily using setInterval or a chained series of setTimeout. I tend to prefer the latter, which looks something like this:

function showValues(a, delay) {
    var index = 0;

    if (a.length !== 0) {
        // If you want a delay before the first one:
        setTimeout(showValue, delay);

        // Alternately, if you want to show the first right away
        // showValue();
    }

    // Function to show one value
    function showValue() {
        // Get the value
        var value = a[index++];

        /* ...show the value however you see fit... */

        // Schedule next display, if any
        if (index < a.length) {
            // Schedule next run
            setTimeout(showValue, delay);
        }
    }
}

Usage:

showValues(["value1", "value2", /* etc. */, 2000); 2000 = two seconds

Live example | source

Upvotes: 4

ThiefMaster
ThiefMaster

Reputation: 318488

Animation functions like fadeIn() make use of the jQuery FX queue so you can use .delay() in the call chain to delay the calling of these functions. In the following example one element is shown every second.

var data = ['foo', 'bar', 'foobar', 'moo', 'meow', 'xxx'];
var list = $('ul');
$.each(data, function(i, value) {
    $('<li/>', { text: value }).hide().appendTo(list).delay(i * 1000).fadeIn();
});

Demo: http://jsfiddle.net/ThiefMaster/frW8s/

Upvotes: 4

Related Questions