DotNetCurry Logo

Advanced Scenarios with the jQuery UI Tab Widget (for HTML as well as ASP.NET websites)

Posted by: Suprotim Agarwal , on 4/13/2015, in Category jQuery and ASP.NET
Views: 15209
Abstract: Learn how to customize the jQuery UI Tab Widget to suit your website requirements.

The jQuery UI Tab Widget organizes content by breaking it into multiple panels, each having a header and content. We will start by seeing the default functionality of the Tab widget and then see some examples of how we can configure the Tab Widget to suit our needs.

To see what we get straight out-of-the-box, go ahead and create a new file ‘jQueryUITab.html’. The structure of the markup is as follows:

<div id="tabs">
    <ul>
        <li><a href="#t1"><span>Tab One</span></a></li>
        <li><a href="#t2"><span>Tab Two</span></a></li>
        <li><a href="#t3"><span>Tab Three</span></a></li>
    </ul>
    <div id="t1">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
    </div>
    <div id="t2">
        Quisque luctus condimentum tellus sed imperdiet.
    </div>
    <div id="t3">
        Cras felis quam, auctor scelerisque convallis eget, suscipit 
    </div>
</div>

We have an outer container div with the id tabs. You can call it anything you want. We then have a list where each list item contains an anchor and represents the Tab Headings. Following the list, we have a number of div elements which represent Tab Content Panels. The Div elements match the number of list items. Although I have put plain text inside each Content Panel, you can put whatever content you want, including images, videos etc.

Note: ASP.NET Developers can use Panel's instead of Divs. Panels get rendered as Divs.

Now add the following references:

<link href="css/jquery-ui.min.css" rel="stylesheet" />
<script src="../scripts/jquery-1.11.1.min.js"></script>
<script src="../scripts/jquery-ui.min.js"></script>

To create the Tabs widget, just use the following code:

<script type="text/javascript">
    $(function () {
        $("#tabs").tabs();
    });
</script>

View the page in the browser and here’s what you get:

s3-tab-default

As you can see, only one Tab is visible at a time. You have to click on the other tabs to view its content.

Live Demo

Some Advanced Scenarios using the jQuery UI Tab Widget

We just used the jQuery UI Tab widget out-of-the-box but there’s a lot of cool stuff that can be done programmatically with the jQuery UI Tab control. Let’s explore them one by one. Create a new file called ‘jQueryUITab-config.html’. The HTML structure remains the same as we saw earlier.

Set the Default Tab

The Tabs widget has an active option to change the currently active Tab panel. To change the Active Panel programmatically, use this code:

$("#tabs").tabs({ active: 1 });

..which sets the default tab to Tab Two by setting the index of the active panel to 1 (zero-based index).

Live Demo

Programmatically switching to a Tab (Using Index)

Let’s say you want to switch to Tab Three programmatically, here’s how you would do it:

$("#tabs").tabs("option", "active", 2);

Since the tabs use a zero based index, we are supplying it with an option of 2.

In versions prior to jQuery UI 1.9, you could use the select method to switch to a tab, but that has been deprecated.

Live Demo

Programmatically switching to a Tab (Using ID)

There seems to be no built-in API that allows you to programmatically switch to a Tab, using it’s ID. However jQuery being so extensible, we can always create our own function. Here’s how:

$.fn.fetchTabID = function (id) {
    $(this).tabs("option", "active", $('#' + id).index() - 1);
};

fetchTabID is a simple function that looks for the Tab using index(). We are doing index() – 1 as Tab indexes are zero based. You can then call this function passing in the Tab ID, which selects the tab with id=t2:

$("#btnTabID").on('click', function () {
    $("#tabs").fetchTabID('t2');
});

Live Demo

Programmatically Add a New Tab

To add a new Tab, you need to inject a new <li> and append it to a <ul> in the tab #tabs. For the content, create a <div> and append it to the #tabs element.

$("#btnAddNew").on('click', function () {
    $("<li><a href='#t4'>Tab Four</a></li>")
    .appendTo("#tabs ul");
    $("<div id='t4'>I was added programmatically</div>").appendTo("#tabs");
    $("#tabs").tabs("refresh");
});

The refresh() method processes any tabs that were added or removed directly in the DOM.

Live Demo

Programmatically Get the ID of the Active Tab

In order to programmatically retrieve the ID of the panel that is currently open, use the active option

$('#tabs').tabs({
    activate: function (event, ui) {
        var activeTab = $('#tabs').tabs("option", "active");
        $("#currtab").text("Current Active Tab :" + activeTab);
    }
});

Clicking through different tabs and the code will print the ID of the clicked tab in a paragraph currtab

Live Demo

 

Capturing Tab Events

To handle interactions, we can use the event callbacks exposed by each component. If you want to capture the index every time the user clicks on the tab, use the active option inside the activate function as shown here:

$('#tabs').tabs({
    activate: function (event, ui) {
        var activeTab = $('#tabs').tabs("option", "active");
        $("#currtab").text("Current Active Tabindex :" + activeTab);
    }
});

You can also use the tab widget's custom binding events and their triggers. For example the same code using a custom tabsactivate event will be like the following:

$("#tabs").on("tabsactivate", function (event, tab) {
    $("#currtab").text("Current Active Tabindex " + tab.newTab.index());
});

We have prefixed the name of the tab with the name of the event. Binding to the tabsactivate event in this way produces the same result as we saw in the previous example.

Live Demo

Retain Tabs across Page Refresh

In a previous article Add Notifications in your Website using jQuery, we had seen how to make use of the cookie plugin to remember user preferences. We will use the same plugin to retain tabs across page refresh.

Add a reference to the plugin:

<script src="../scripts/jquery.cookie.js"></script>

..and use the following code:

$("#tabs").tabs({
    active: $.cookie('currenttab'),
    activate: function (event, ui) {
        $.cookie('currenttab', ui.newTab.index(), {
            expires: 30
        });
    }
});

In the code above, when any tab is clicked, we are using the jQuery Cookie plugin here to set a cookie called currenttab which will store the index of the currently selected tab for 30 days. When the user revisits the page, the cookie will be read and the active tab will be set to last saved tab.

View the page in your browser, select Tab3 and close the page. Now reopen the page and you will see that the page loads with Tab3 selected.

Live Demo

Add a Custom Theme to Tabs

The tabs widget uses the jQuery UI CSS framework to style its look and feel. However you can very easily change the basic appearance of a tab using a custom stylesheet. You can either look up the jQuery UI tab CSS file or you can use Chrome Developer Tools, or Firebug in Firefox, or F12 in IE to find out the class names added to the underlying HTML elements, and override them in your CSS. For eg: Here are the class names added to the tab as viewed in Chrome.

s3-ui-custom-class

We will override the .ui-widget-header, .ui-widget-content, .ui-state-default and .ui-state-active which represents the header, content, default and active state of the tab; to customize our tab.

Save the following custom css in a file called customtheme.css in the css folder.

#tabs { 
    padding: 10px; 
    border: 1px solid #4c4c4c; 
    background: #55acee; 
}

.ui-widget-header { 
    background:#7fb6dc;
    font-size:16px;
    font-weight:600;
    transition:all linear 0.30s;
}

#tabs .ui-widget-content { 
    padding:10px;
    border-radius: 5px;
    background: #fff; 
    font-size: 80%; 
}

.ui-state-default, .ui-widget-content .ui-state-default { 
    box-shadow:-1px 1px 1px rgba(0,0,0.15,0.15);
    background:#a7dde5; 
}

.ui-state-active, .ui-widget-content .ui-state-active { 
    background:#fff;
    color:#4c4c4c;  
}

Add the reference to this new stylesheet in the <head> section after the jquery-ui.min.css file

<link href="CSS/jquery-ui.min.css" rel="stylesheet" />
<link  href="CSS/customtheme.css" rel="stylesheet" />

And that’s it. Run the example and you have a Tab Control with a custom theme applied to it.

s3-custom-theme-tab

Live Demo

Carousal Tabs

The rotate method which allowed you to enable rotation for Tabs, was removed in jQuery UI 1.9 as the team felt it was fairly uncommon and unrelated to the core functionality of tabs. Christopher McCulloh has implemented an extension which is based on the original code and adds back the rotate method for those who need it.

You can download the script from here - https://github.com/cmcculloh/jQuery-UI-Tabs-Rotate

Once downloaded, add the script reference:

<script src="../scripts/jquery-ui-tabs-rotate.js"></script>

..and call the rotate method in the following manner:

$("#tabs").tabs().tabs("rotate", 3000, true);

This will create a carousal effect and a new tab will be selected every 3 seconds

Live Demo

Hope you enjoyed these tips. If you liked this article, take a look at my new book The Absolutely Awesome jQuery Cookbook which contains scores of practical jQuery/jQueryUI recipes you can use in your projects right away.

Was this article worth reading? Share it with fellow developers too. Thanks!
Share on Google+
Further Reading - Articles You May Like!
Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!