Search code examples
jquery-uijquery-ui-tabs

How to set active tab of jquery ui tabs using custom function?


I want to set active tab in jquery ui tabs based on output of a function active_tab(), but active_tab() function do not run when tabs are initialized.

function active_tab()
{
    var t = 1;
    // some conditions
    return t;
}

$( "#tabs1" ).tabs({
    active: function(){
        active_tab();
    }
});

Solution

  • jQuery UI Tabs option for active expects a number, true, or false.

    Which panel is currently open. Multiple types supported:

    • Boolean: Setting active to false will collapse all panels. This requires the collapsible option to be true.
    • Integer: The zero-based index of the panel that is active (open). A negative value selects panels going backward from the last panel.

    I would advise the following type of code:

    function active_tab(tbs, i){
      if(i == undefined){
        i = 0;
      }
      // Add Other Conditions
      tbs.tabs("option", "activate", i);
      return i;
    }
    
    $("#tabs1").tabs();
    
    activate_tabs($("#tabs1"), 1);
    

    Another method would be:

    function active_tab(){
      var t = 1;
      // some conditions
      return t;
    }
    
    $("#tabs1").tabs();
    $("#tabs1").tabs("option", "activate", activate_tab());
    

    You can also do the following:

    $("#tabs1").tabs({
      activate: activate_tab()
    });