Any help on this problem would be appreciated. I have a main navigation like so:
<ul>
<li><a href="">Nav 1</a></li>
<li><a href="">Nav 2</a></li>
<li><a href="">Nav 3</a></li>
<li><a href="">Nav 4</a></li>
</ul>
Somewhere below there is a content div like so:
<div id="content">
<div class="block-1">
<p>Lorem ipsum</p>
</div>
<div class="block-2">
<p>Lorem ipsum</p>
</div>
<div class="block-3">
<p>Lorem ipsum</p>
</div>
<div class="block-4">
<p>Lorem ipsum</p>
</div>
</div>
The #content div has display:none; set in the stylesheet. As do each of the blocks inside it. When someone clicks a nav item I would like it to show the content container, with only that block the corresponds to it. Nav1 = block-1 etc… When you click another link it hides the other and shows the new selection.
Any ideas?
I’ve written a quick JSFiddle for you. Using jQuery’s
.index()method, you can get the index of the clicked link, and use that to show the correct div. I’ve used a class in the following code to show/hide your div. You could replace this with an extra bit of logic to fade each div, for example.Another point to make is you don’t need the
-1,-2, etc postfixes on the divs;index()and the:eq()selector handles this for you. I’ve changed your HTML slightly and here is the JS:JavaScript
HTML
In response to the comments, here’s an update example that will hide every element when the first
liis clicked. To make it more versatile, you could add a class (say,hideall) to theliand use.hasClass("hideall")inside theif()instead ofindex == 0, which checks to see if this is the firstliin the list. JSFiddle here, JS below. I’ve edited the HTML in the Fiddle a little.