Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Plugin: Using setInterval to periodically update an array of jQuery elements

Tags:

jquery

plugins

I'm writing a jQuery plugin which introduces a new method foo(), which creates some <img> element within the DOM object it is called on. I store the pointers to these images in an array images. At the end of the method, I call setInterval("someFunction(images)", 1000) which should periodically perform some actions (e.g. change the src) on the images.

Here is a very short version of what my code looks like:

(function($) { 
$.fn.foo = function () {
return this.each (function () {
    $box = $("#"+this.id);

    images = new Array();
    for (i = 0; i<4; i++) {
        images[i] = $("<img>");
        $box.prepend(images[i]);
    }

    setInterval("someFunction(images)", 1000);
});
}
function someFunction(images) {
    for (i = 0; i<images.length; i++) {
        images[i].attr("src", "foo"+(parseInt(Math.random()*5)));
    }
}
})(jQuery);

Everything works if I apply foo() to a single element, but if I apply it to multiple elements, all the periodic updates are applied to the last element. I assume this is because the array is passed as a reference to someFunction, and is then overwritten.

I tried to use slice() on the array to create a copy, but that did not work, though I don't understand why. I think what I'm looking for is to somehow store the pointers to my images within their parent container.

Any help would be appreciated on what I need to change so that all the images are updated and not just the ones in the last container.

like image 847
Waboodoo Avatar asked Feb 01 '26 16:02

Waboodoo


1 Answers

How about this then:

(function ($) {
    $.fn.foo = function () {
        return this.each(function () {
            $box = $(this); // Changed to "this"

            var images = new Array();
            for (i = 0; i < 4; i++) {
                images[i] = $("<img>");
                $box.prepend(images[i]);
            }

            // Added the function inline.
            setInterval(function () {
                for (i = 0; i < images.length; i++) {
                    images[i].attr("src", "foo" + (parseInt(Math.random() * 5)));
                }
            }, 1000);
        });
    };
})(jQuery);

EDIT:

You could also try it like this if you want to reuse someFunction:

(function ($) {
    $.fn.foo = function () {
       ...
            setInterval(function () {
                someFunction(images);
            }, 1000);
       ...
    };
})(jQuery);

function someFunction(images) {
    for (i = 0; i<images.length; i++) {
        images[i].attr("src", "foo"+(parseInt(Math.random()*5)));
    }
}
like image 153
Mario S Avatar answered Feb 03 '26 04:02

Mario S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!