Simple jQuery Navigation Tutorial [Work in progress]

Jun 27, 02:03 PM

simple jquery navigation

This simple jQuery navigation example makes use of two of my favorite functions that play oh-so-nice together, index() and each(). With these, there is no need to specify anything. Simply add buttons and corresponding content in the HTML and the iterators match content by comparing indexes. Let me explain...

Step 1: Create HTML Page

The first step is creating the structure of your content. Order is everything in this example. Below I have recreated a common navigational metaphor: button represents content to be displayed.

 1 <html>
 2 <head>
 3 <title>Simple jQuery Navigation</title>		
 4 </head>
 5 <body>
 6 <div id="container">
 7   <div id="button-group">
 8     <div class="button selected">
 9       <div class="button-num selected">1</div>
10     </div>
11     <div class="button">
12       <div class="button-num">2</div>
13     </div>
14     <div class="button">
15       <div class="button-num">3</div>
16     </div>
17     <div class="button">
18       <div class="button-num">4</div>
19     </div>
20     <div class="button last">
21       <div class="button-num">5</div>
22     </div>
23   </div>
24   <div id="content">
25     <div class="page"><div class="page-num">1</div><p>Lorem ipsum dolor ...</p></div>
26     <div class="page"><div class="page-num">2</div><p>Sed interdum pharetra ... </p></div>
27     <div class="page"><div class="page-num">3</div><p>Cras dui elit...</p></div>
28     <div class="page"><div class="page-num">4</div><p>Duis nec dui augue...</p></div>
29     <div class="page"><div class="page-num">5</div><p>Cras rhoncus...</p></div>
30     </div>
31   </div>
32 </div>
33 </body>
34 </html>

But what is the point of a button if all the content is shown anyway?

Step 2: Add jQuery

Now we can add code to show and hide the appropriate content, while giving addition visual cues to enhance usability. First, the jQuery library must be included in some manner.

1 <script type="text/javascript" src="jquery-1.3.2.min.js"></script>

Create a document ready function so to execute our functions on page load.

1 <script type="text/javascript">
2    $(document).ready(function(){
3
4    });							
5 </script>

Start by hiding all the 'page' divs, and then slideDown() the 1st child.

1 $(document).ready(function(){
2 										 
3   $("div.page").hide();
4   $("div.page").eq(0).slideDown();	
5 
6 });

Now add a click() event to all the "button" divs. This will control the rest of the behavior in this concept.

1 $("div.button").click(function() {
2 
3   $('div.button').each(function() {
4     $(this).removeClass("selected").children().removeClass("selected");											
5 
6   });
7   $('div.page').each(function() {
8     $(this).hide();											
9 
10   });
11 });
Katie O'Connor

,

---

Commenting is closed for this article.

---