Search code examples
jquery-ui-tabscycle

Cycle Jquery UI Tab on "previous" and "next" button


I am using Jquery UI Tabs for my website.

<script type='text/javascript'>
//<![CDATA[ 
jQuery(window).load(function(){
jQuery('#myTabs').tabs({ fx: { opacity: 'toggle' }});

jQuery('.next-product').click(function(){ 
var jQuerytabs = jQuery('#myTabs').tabs();
var selected = jQuerytabs.tabs('option', 'selected');
jQuerytabs.tabs('select', selected+1);
});

jQuery('.previous-product').click(function(){ 
var jQuerytabs = jQuery('#myTabs').tabs();
var selected = jQuerytabs.tabs('option', 'selected');
jQuerytabs.tabs('select', selected-1);
}); 

As you can see that i have been using the previous next button to move from one tab to another. My question is "When i click on next and if the last tab is open then automatically the first tab should get open, and similarly When i click on previous and if the first tab is open then automatically the last tab should get open"

Please help me out, i am stuck from over 3 days now and no solution. I have searched a lot on net but no solution for this.


Solution

  • You can count the number of .ui-tabs-panel elements.

    jQuery(window).load(function() {
    
        var $tabs = jQuery('#myTabs');
    
        $tabs.tabs({
            fx: {
                opacity: 'toggle'
            }
        });
    
        var amount = $tabs.find('.ui-tabs-panel').length;
    
        jQuery('.next-product').click(function() {
            var selected = $tabs.tabs('option', 'selected');
            $tabs.tabs('select', selected + 1 === amount ? 0 : selected + 1);
        });
    
        jQuery('.previous-product').click(function() {
            var selected = $tabs.tabs('option', 'selected');
            $tabs.tabs('select', selected === 0 ? amount - 1 : selected - 1);
        });
    
    });
    

    DEMO

    Notes:

    • select your tab element already and re-use the selector var $tabs = jQuery('#myTabs');, it'll be more efficient
    • no need to re-call .tabs() on your click handlers