Instant JavaScript Tab Menu Revealing DIVs Tutorial


This is a quick tutorial or a note on how to make your tabs content display instantly on-click, rather than have to reload the page and send them to a new page. This is really simple and not formatted but illustrates the concept, plus I just wrote it up for one of my friends so it’s perfect to post here for everyone else.

Here is the code:

START HTML:

<!-- ###### Tabs/Links -->

<a href="javascript:void()" onclick="seediv('features')">Features</a>
<a href="javascript:void()" onclick="seediv('prices')">Prices</a>
<a href="javascript:void()" onclick="seediv('demo')">Demo</a>

<!-- ###### Divs Holding Content -->

<div id="features" style="display:block;">
	Features content stuff goes here. 
	Because this is the main div, it will display by default that is why 
	it's display is set to block, so it is visible but others are hidden 
	with display:none;
</div>

<div id="prices" style="display:none;">
	Prices content stuff goes here
</div>

<div id="demo" style="display:none;">
	Demo content stuff goes here
</div>

<script language="javascript">

<!-- ###### JavaScript function to handle the action -- >

function seediv(whichdiv) {

	// ###### Hides all the content DIVs first
	document.getElementById('features').style.display='none';
	document.getElementById('prices').style.display='none';
	document.getElementById('demo').style.display='none';

	// ###### Then displays only the one that was called
	document.getElementById(whichdiv).style.display='block';

}

</script>

/ END HTML

Now take a look at it, you have the navigation at the top, notice the href is using JavaScript to void out the redirect and instead initiating a JavaScript function using the onclick parameter. Each link is passing it’s div id value to the function so it knows which DIV to display.

Second, we have the divs that are holding the content for each of the tabs. Only the main div is set to be visible using style=”display:block;”, the others are set to none, so they are hidden until their tab is clicked.

Thirdly, the JavaScript function. It listens for a call with a value and as soon as it receives that value, it hides all the divs and then only displays the one that has the value that was passed to it.

That’s is. This is a basic concept of a JavaScript instant tabs content displaying… or whatever you would call this.

Do you have a better, or a different way of doing this? I’d love to see it. Please add it in the comments.

If you liked this post, share it with your friends!

One Comment

  1. Johan says:

    hey, just wanted to know if u have a solution in makeing the transition to the other content in smooth fade or somthing like that ? :)

Please Leave Your Comment

Please make sure to enter the required information where indicated. We moderate all comments so please no link dropping; do not spam, and do not advertise!
 

Name (required):

Email (will not be published) (required):

Website:

Comment: