Andre
Andre

Reputation: 77

jQuery Cycle2 Change number of slideshow elements by resizing window

I'm building a responsive design for both desktop and tablet view. In this design I'm using one or more slideshow build with jQuery Cycle2. This slideshows containts in the desktop 3 objects in a slider and in the tablet version just 2.

My approach: I'm checking for a window resize event, unwrap all cycle captions, wrap the new ones around the given number of elements and reinit the cycle plugin.

My problem: Everything works fine till I'm trying to reinit the cycle plugin. It just don't work without any failure or something. So just the reinit seems to be the problem.

My code:

//function to fire the resize event when its done
var delay = (function(){
    var timer = 0;
    return function(callback, ms){
    clearTimeout (timer);
    timer = setTimeout(callback, ms);
    };
})();

$(window).resize(function() {
    delay(function(){
        if( window.innerWidth <= 979 ){
            resizeWrapper( 2 );
        }
    }, 500);
});

//function for delete wrappers and wrap new ones based on a given number
function resizeWrapper( numberOfItems ){
    $( '.productsItem' ).unwrap();

    var $set_latestProductsCycle = $( '#latestProductsCycle' ).children();
    for( var i=0, len = $set_latestProductsCycle.length; i < len; i+=numberOfItems ){
        $set_latestProductsCycle.slice( i, i+numberOfItems ).wrapAll( '<div class="popularProductsWrapper"/>' );
    }
    $( '#latestProductsCycle' ).cycle({
        fx: 'scrollHorz',
        prev: '#latestProductsButtonLeft',
        next: '#latestProductsButtonRight',
        timeout: 0,
        caption: '.popularProductsWrapper'
    });
}

Thanks for help.

Upvotes: 0

Views: 1645

Answers (1)

Andre
Andre

Reputation: 77

To answer the question by myself:

I forgot to remove the sentinel container, which will be created, when you first call the cycle script. Furthermore when I reinit the cycle container it's not necessary to define a "caption".

In short the function should look like this:

    function resizeWrapper( cycleContainer, numberOfItems ){
    $( cycleContainer ).cycle( 'destroy' );
    $( cycleContainer + ' .cycle-sentinel' ).remove();

    $( cycleContainer + ' .slider .item' ).unwrap();

    var $set_latestProductsCycle = $( cycleContainer ).children();

    for( var i=0, len = $set_latestProductsCycle.length; i < len; i+=numberOfItems ){
        $set_latestProductsCycle.slice( i, i+numberOfItems ).wrapAll( '<div class="slider"/>' );
    }

    $( cycleContainer ).cycle({
        fx: 'scrollHorz',
        prev: cycleContainer + 'Prev',
        next: cycleContainer + 'Next',
        timeout: 0
    });
}

Thanks for everybodies attention.

Upvotes: 3

Related Questions