Jayesh Patel
Filed under - JavaScript, jQuery, Web Designer Help
No Comments so far. Add yours now

I am learning jQuery and really loving it! Here’s a simple bit of code I wrote to achieve an interface element. It’s basically tabs — there’s a list of links and when you click one the corresponding content is shown. It assumes there’s an equal number of links and content blocks. And that they’re in the same order. The HTML is like so:


<ul id="slidecontrols">
	<li><a href="#one">One</li>
	<li><a href="#two">Two</li>
</ul>

<div id="slides">
	<div>This is content block One</div>
	<div>This is content block Two</div>
</div>

 

The # links / id’s on the content div’s are to give some functionality for people without JavaScript. Here’s the jQuery:

 

Selec All Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
$(document).ready(function() {
 
	//Set the initial state: highlight the first button...
	$('#slidecontrols').find('li:eq(0)').addClass('selected');
 
	//and hide all slides except the first one
	$('#slides').find('> div:eq(0)').nextAll().hide();
 
	//actions that apply on click of any of the buttons
	$('#slidecontrols li').click( function(event) {
 
		//turn off the link so it doesn't try to jump down the page
		event.preventDefault();
 
		//un-highlight the buttons
		$('#slidecontrols li').removeClass();
 
		//hide all the slides
		$('#slides > div').hide();
 
		//highlight the current button
		$(this).addClass('selected');
 
		//get the index of the current button...
		var index = $('#slidecontrols li').index(this);
 
		//and use that index to show the corresponding slide
		$('#slides > div:eq('+index+')').show();
 
	});
 
});

 

Simple! Best wishes to you in your coding!

Leave your comment

You must be logged in to post a comment.

Share IT © 2018. All rights reserved.