Search code examples
jqueryimagedictionaryslideshowjquery-backstretch

Supply images for slideshow dynamically from HTML (jQuery map/get)


I am using awesome plugin jQuery BackStretch for my background slideshow. This is the common way how to pass images to it.

$.backstretch([
    "http://dl.dropbox.com/u/515046/www/outside.jpg", 
    "http://dl.dropbox.com/u/515046/www/garfield-interior.jpg", 
    "http://dl.dropbox.com/u/515046/www/cheers.jpg"
], {duration: 3000, fade: 750});

I don't want to supply images for it by hardcoding though, I want the function to grab what my PHP generates inside that container. Here's what I have so far.

var images = $('#background img').map(function() { return this.src; }).get();
$.backstretch([$images], {duration: 3000, fade: 750});

And that, obviously, doesn't work - according to FireBug, variable images is not defined (?) . although if I "alert" the variable, it shows comma separated urls of images.

Any idea what am I doing wrong? Thank you!


Solution

  • This should be suffice. backstretch is expecting the first argument to be an array of strings that are references to images.

    $(document).ready(function () {
        var images = [];
    
        // iterate over your selection
        $('#background img').each(function () {
            // save source to list
            images.push(this.src);
        });
    
        // use plugin
        $.backstretch(images, {duration: 3000, fade: 750});
    });
    

    Also I'm assuming your HTML is something like this...

    <div id="background">
        <img src="http://dl.dropbox.com/u/515046/www/outside.jpg" />
        <img src="http://dl.dropbox.com/u/515046/www/garfield-interior.jpg" />
    </div>