Link to home
Start Free TrialLog in
Avatar of SonicVoom
SonicVoomFlag for United States of America

asked on

jQuery: assign list of buttons to toggle a list of elements

I need a simple script that will create event handlers on all <li>'s in two navigation menus. The two menus are the same, one at the top of a page, one at the bottom. They will toggle the visibility of content <div>'s.

I want a click on the first <li> to be actionable (show target, hide others) on the first <div>. The second <li> on the second <div>, etc for any number of <div>'s and <li>'s.

Thanks
Avatar of cmalakar
cmalakar
Flag of India image

Can you post your html with li and div elements ?
Each div is associated with li.

Adding a click event for li, to find its div and alerting the html content.
$(function(){
  $("li").bind("click", function(){
   alert($(this).find("div").html());
});
});

<div id="hello">
<ul>
    <li>first div <div>first div content</div></li>
    <li>second div <div> second div content</div></</li>
</ul>

<ul>
    <li>third div <div>third div content</div></li>
    <li>fourth div <div>fourth div content</div></li>
</ul>
</div>

Open in new window

Avatar of SonicVoom

ASKER

Thanks for clarifying my lack of... clarity.

Here's what I meant. Clicking the first labelA would display only content1, labelB displays only content2, etc. It's not the show/hide technique I'm looking for as much as keeping the code dynamic and capable of handling any number of label/content pairs.

I've got each() in mind, but I'd need to get the current index of the each() iteration, and use it to access the child of #content that corresponds to that index. How is this done?

<div id="Main">
	<div class="sidebar">
		<ul class="mainNav">	
		<li><a>labelA</a></li>	
		<li><a>labelB</a></li>	
		<li><a>labelC</a></li>	
		<li><a>labelD</a></li>	
		</ul>
	</div>
	<div id="Content">
		<div>Content1</div>
		<div>Content2</div>
		<div>Content3</div>
		<div>Content4</div>
	</div>
	<div class="footer">
		<ul class="mainNav">	
		<li><a>labelA</a></li>	
		<li><a>labelB</a></li>	
		<li><a>labelC</a></li>	
		<li><a>labelD</a></li>	
		</ul>
	</div>
</div>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of dnzone88
dnzone88
Flag of Malaysia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Check with this...
$(document).ready(function(){
	$('#Content div').hide();
	
	$('ul.mainNav li').bind('click', function(){
		var idx = $('ul.mainNav li').index(this);
		$("#Content div").each(function(index,eachDiv){
              if(idx == index){
                 $(eachDiv).toggle();
              }
            });
	});
});

Open in new window

SonicVoom, Are you sure that the solution provided by dnzone88 works for your problem ?