Reputation: 45
I have the following html structure:
<div class="links">
<a href="#link_1">Link 1</a>
<a href="#link_2">Link 2</a>
<a href="#link_3">Link 3</a>
</div>
<div id="link_1" class="item open">
<h3>Title 1</h3>
<div class="details">
<p>Lorem Ipsum dolor sit</p>
</div>
</div>
<div id="link_2" class="item">
<h3>Title 2</h3>
<div class="details">
<p>Lorem Ipsum dolor sit</p>
</div>
</div>
<div id="link_3" class="item">
<h3>Title 3</h3>
<div class="details">
<p>Lorem Ipsum dolor sit</p>
</div>
</div>
By default some of the 'item' div(s) will be open. I am adding a click event to '.links a'. I need to add an 'open' class for the corresponded item group.
Currently it's adding '.open' to all 'div.item' http://jsfiddle.net/rmbor/boc0c6ef/
Any help with explanation are highly appreciated
Upvotes: 1
Views: 52
Reputation: 67207
Try to rewrite your logic like below,
var $href = $('.links a[href^="#"]');
$href.on('click', function(e) {
e.preventDefault();
$(this).parent().siblings('.item').eq($href.index(this)).addClass("open");
});
$(document).on('click', 'h3', function(e) {
e.preventDefault();
$(this).closest('.item')
.toggleClass('open');
});
Find the index
of corresponding anchor
tags. By using it access the relevant target elements and add class to it.
Upvotes: 2