I have multiple divs called .details, and I want to apply the following click functions to them. But right now if I click on one li, all li’s with the same class names change throughout all the divs called .details. How do I only apply the click function to the current .details div?
$(document).ready(function() {
$('.details div.two').hide();
$('.details div.three').hide();
$('.details ul li.one').click(function () {
$(this).addClass('active');
$('.details ul li.two').removeClass('active');
$('.details ul li.three').removeClass('active');
$('.details div.one').show();
$('.details div.two').hide();
$('.details div.three').hide();
});
$('.details ul li.two').click(function () {
$(this).addClass('active');
$('.details ul li.one').removeClass('active');
$('.details ul li.three').removeClass('active');
$('.details div.one').hide();
$('.details div.two').show();
$('.details div.three').hide();
});
$('.details ul li.three').click(function () {
$(this).addClass('active');
$('.details ul li.one').removeClass('active');
$('.details ul li.two').removeClass('active');
$('.details div.one').hide();
$('.details div.two').hide();
$('.details div.three').show();
});
});
HTML
<div class="details">
<ul>
<li class="one active"><span>Nav 1</span></li>
<li class="two"><span>Nav 2</span></li>
<li class="three"><span>Nav 3</span></li>
</ul>
<div class="one">
<p>Content 1</p>
</div>
<div class="two">
<p>Content 2</p>
</div>
<div class="three">
<p>Content 3</p>
</div>
</div>
CSS
.active {background:#fff;}
Go back to the top with
closestand then come back down withfind:Similarly for the other two.
You could further clean things up with a bit of generalization and then you’d only need one
.clickcall instead of three; something like this.Demo: http://jsfiddle.net/ambiguous/2zYt3/