Search code examples
javascriptjqueryresizewindowcarousel

Reload jQuery Carousel on window resize to change orientation from vertical to horisontal


I'm creating a gallery for a responsive lay-out - I am using jQuery Riding Carousels for the thumbnails.

When the window is re-sized to smaller than 1024px, the orientation of the carousel needs to change from vertical to horizontal ...

I'm doing it like this at present:

<script type="text/javascript">
jQuery(document).ready(function() {
  jQuery('#mycarousel').jcarousel({
    vertical: $(window).width() > 1008,
    scroll: 3,
  });
});
</script>

... the JS simply hooks up a class, but it doesn't do so if you re-size the browser window by dragging it - you need to refresh the page.

Is there a way to destroy the script and re-initialize it on the fly?


Solution

  • Please check Working exmpale: http://codebins.com/bin/4ldqpba/1/Jcarousel%20vertical%20on%20resize Tested in all browsers and works perfectly fine. bounty is mine :) In the example i have give threshold widht 350 you can test it by resizing the result pane and as soon as you start havin horizontal scroll bar it will converted to vertical.

    1 possible issue depending on your requirement is if you ahve any handlers on images they will be gone after changing display way. the solution for it is wrap your #mycarousel in a div and use Jquery delegate to handle events on the wrapper so no issue with events also. Let me know if you come under this situation.

    Following code is exactly as per your need.

    When the window is re-sized to smaller than 1024px, the orientation of the carousel needs to change from vertical to horizontal .

    which is revers form the example as for me it makes more sense if width is less make it vertical.

    jQuery(document).ready(function() {
        var widthCheck = 1008;
        var resizeTimer = null,
            verticalFlg = $(window).width() > widthCheck;
        var obj = jQuery('#mycarousel').clone();
        $('#mycarousel').jcarousel({
            vertical: verticalFlg,
            scroll: 2
        });
        jQuery(window).resize(function() {
            resizeTimer && clearTimeout(resizeTimer); // Cleraring old timer to avoid unwanted resize calls.
            resizeTimer = setTimeout(function() {
                var flg = ($(window).width() > widthCheck);
                if (verticalFlg != flg) {
                    verticalFlg = flg;
                    $('#mycarousel').closest(".jcarousel-skin-tango").replaceWith($(obj).clone());
                    $('#mycarousel').jcarousel({
                        vertical: verticalFlg,
                        scroll: 2
                    });
                }
            }, 200);
        });
    })