Question

I am working on an page using jQuery tabs. The example shows how to set a cookie when a tab is selected. However, what I would like to do instead is to use a button to ask the user to make a conscious decision to select a particular tab as his/her default tab.

I've added a button to the content of each tab, with a value equivalent to the tab anchor value. For the moment clicking only displays an alert message.

Can someone help me to associate the button click with setting the cookie to the tab value. I've set up a jsfiddle to show what I am trying to accomplish. Any help would be greatly appreciated!!

http://jsfiddle.net/lbriquet/eLx2d/15/

    $(function() {
    $( "#tabs" ).tabs({
        select: function(event, ui) {                   
           window.location.replace(ui.tab.hash);
        },
        cookie: {
            // store cookie for a day, without, it would be a session cookie
            expires: 1
        }                        
    });
    $(".my_button").click(function() {
        alert($(this).attr("value"));
    });  
});
Was it helpful?

Solution

You can use $.cookie directly to provide your custom behaviour. In a nutshell on creation of the tabs controls (in the create event) check to see if there is a cookie value. If so then set the selected tab based on the value. And store it on click of the button:

$(function() {
    $( "#tabs" ).tabs({
        select: function(event, ui) {                   
           window.location.replace(ui.tab.hash);
        },
        create: function(e, ui) {
            var tabs = $(e.target);
            // Get the value from the cookie
            var value = $.cookie('selected-tab');

            if(value) {
                console.log('Setting value %s', value);
                // Set which tab should be selected. Older jQuery UI API
                tabs.tabs('select',value);                
            }
        },                   
    });
    $(".my_button").click(function() {
       var value = $(this).attr("value");
       console.log('Storing tab %s', value);
       // Store value with key "selected-tab" and set it to expire
       // in one day. 
       $.cookie('selected-tab', value, {expires: 1});
    });  
});

In newer versions of jQuery UI (verified on 1.9+) you need to use the active options with a tab index to select the tab.

Example:

  //store as value in above example or dynamically find index based on the id
  var selectedIndex = 1;

  $('#tabs').tabs('option', 'active', selectedIndex);

  // Or even better pass the active index when creating the tabs control
  $('#tabs').tabs({ active: selectedIndex });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top