Creating tab navigation
jQuery UI is built from the core interaction plugins of jQuery. As a high-level framework, it makes creating effects and animation easy for every developer. Now we will build a tab navigation using jQuery UI.
Getting ready
First of all, we need to include the jQuery library from www.jquery.com, if we haven't done it in the preceding recipe. Then, we can download jQuery UI library from www.jqueryui.com/download. On this page, we can download specific modules or the whole library. We can select the theme we like or create our own one with advanced theme settings. For now, we will select the whole library with the ui-lightness
theme.
How to do it...
Now we are ready for coding. Let's start with the HTML part. This part will define a
navigation
element with three tabs and one accordion.<body> <div id="navigation"> <ul> <li><a href="#tabs-1">Home</a></li> <li><a href="#tabs-2">Our Books</a></li> <li><a href="ajax/shop.html">Shop</a></li> </ul> <div id="tabs-1"> <p>Lorem ipsum dolor 1</p> </div> <div id="tabs-2"> <p>Lorem ipsum dolor 2</p> </div> </div> </body>
When the HTML is ready, we can continue with CSS and JavaScript CSS styles in the
<head>
tag, as shown in the following code:<head> <link href="css/ui-lightness/jquery-ui.custom.css" rel="stylesheet" /> </head>
We will add JavaScript before closing the
<body>
tag:<script src="js/jquery.min.js"></script> <script src="js/jquery-ui.custom.min.js"></script> <script> $(document).ready(function(){ $('#navigation').tabs(); }); </script> </body>
Our result looks like the following:
How it works...
The downloaded jQuery UI contains the whole CSS content of the selected theme (jquery-ui.custom.css
). All we need to do is to include it in the <head>
tag:
... <link href="css/ui-lightness/jquery-ui.custom.css" rel="stylesheet" />
After CSS, we include jQuery and the jQuery UI library:
<script src="js/jquery.min.js"></script> <script src="js/jquery-ui.custom.min.js"></script>
The JavaScript part is really simple:
$('#navigation').tabs();
It is important to fit the required HTML structure. Each hyperlink is targeting the HTML content in selected <div>
tags. To create a relation between them we will use #id
in each hyperlink and the ID of the selected <div>
tag (for example, tabs-1
).
There is an exception in the third tab, which loads the requested data via Ajax. In this case, we do not define any target area, as it will be created automatically. As you can see, using the Ajax in jQuery UI is really easy and comfortable.
There's more...
jQuery UI offers us a lot of options. We can use just a default functionality as was presented in the preceding code snippet or some additional functionality:
Content via Ajax: |
|
Open on mouseover: |
|
Collapse content: |
|
Sortable: |
|
Cookie persistence: |
|
See also
Chapter 3, Useful tools using jQuery