Search code examples
jqueryslideshowslidesjs

Dynamically add items to jquery slideshow


I'm trying to add items to a jquery slideshow ( slides ) but i can't find a way to refresh it. I have this html code:

<a class='add' href='#'>add slide</a>

<div id="slides">   
    <div class="slides_container">    
            <h1>Slide 1</h1>       
            <h1>Slide 2</h1>       
            <h1>Slide 3</h1>       
            <h1>Slide 4</h1>       
            <h1>Slide 5</h1>       
   </div>
</div>

and this js:

$(function() {
    $("#slides").slides();

    $('.add').live('click', (function() {
        $('.slides_control').append('<h1>Slide added</h1>');
        // note: slides_control div is added by the slides plugin automatically and is the real container of the items.
        return false;
    }));

});

The demo is in fiddle

I need to reload the slideshow to show new data but i can't find a way to do it.


Solution

  • The newest version of Slides (see Github) actually does have a function slides('update'), but the current version doesn't have that yet.

    In the meantime, you can use this little hack:

    $("#slides").slides();
    
    $('.add').on('click', function() {
        var children = $('#slides .slides_control').children();
        var newContainer = $('<div class="slides_container" />');
        var slides = $('#slides');
    
        slides.empty().append(newContainer);
        newContainer.append(children);
        newContainer.append('<div><h1>New slide</h1></div>');
    
        slides.slides();
    
        return false;
    });
    

    You can play with it here: http://jsfiddle.net/R7zvM/

    Please note that you should probably do some testing before using this in production code. It seems pretty stable, but your mileage may vary.

    P.S. the .live() method is deprecated as of jQuery 1.7. In this example you did't need event delegation, anyway, but if you ever do you should use the new syntax:

    $(document).on('click', 'a.add', function() {
        console.log('Do something');
    });