Reputation: 12598
I am using this jQuery snippet to show / hide content when a link is clicked..
jQuery(document).ready(function() {
jQuery('.showSingle').on('click', function () {
jQuery(this).addClass('selected').siblings().removeClass('selected');
jQuery('.targetDiv').hide();
var selector = '#div' + jQuery(this).data('target');
jQuery(selector).show();
});
});
http://jsfiddle.net/W4Km8/7947/
For some reason the selected class is not being removed when another link is clicked on, where am I going wrong?
Upvotes: 0
Views: 53
Reputation: 1522
You can use this also by just two changes in your code: Find the "closest" div of ".showSingle" class 1st change : Change first line of HTML
<div class="col-md-4 p_link">
<a class="showSingle" data-target="1">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam iaculis orci id nulla aliquet fermentum. Suspendisse ultrices nulla id magna cursus blandit.
</a>
</div>
<div class="col-md-4 p_link">
<a class="showSingle" data-target="2">Sed feugiat fringilla lacus, quis aliquam turpis cursus eu. In dignissim ultrices tellus in convallis. Sed euismod tellus vel lorem</a>
</div>
2nd Change : 3rd line of js script code
jQuery(document).ready(function() {
jQuery('.showSingle').on('click', function () {
jQuery(this).closest('div').addClass('selected').siblings().removeClass('selected');
jQuery('.targetDiv').hide();
var selector = '#div' + jQuery(this).data('target');
jQuery(selector).show();
});
});
Upvotes: 0
Reputation: 196002
The problem is that the a
links are not siblings, so the .siblings()
call does not select the other links.
You should use (for your html)
jQuery(this).addClass('selected')
.closest('.p_link')
.siblings()
.find('.showSingle')
.removeClass('selected');
Demo at http://jsfiddle.net/W4Km8/7951/
But this will still not work perfectly on your structure because it is not consistent. (it will not work on the first link, because the .p_link
is nested inside one more div
than the others)
An alternative (for this adhoc structure) could be
jQuery('.showSingle.selected').removeClass('selected');
jQUery(this).addClass('selected');
Demo at http://jsfiddle.net/W4Km8/7950/
Upvotes: 4