Mella Mella - 5 months ago 9
Javascript Question

function targeting only clicked element

i have a page with several accordeons, which are working, but the js is affecting all accordeons and not only the clicked on accordeon as it should be. how does the JS needs to be changed that only the "clicked on" accordeon changes?

heres the js:

jQuery(document).ready(function(){

jQuery('ul.tabs li').click(function(){
var tab_id = jQuery(this).attr('data-tab');

jQuery('ul.tabs li').removeClass('current');
jQuery('.tab-content').removeClass('current');

jQuery(this).addClass('current');
jQuery("#"+tab_id).addClass('current');
})

})


and here one of the accordeons:

<div class="mytabcontainer">
<ul class="tabs">
<li class="tab-link current" data-tab="A-1">BUTTON A</li>
<li class="tab-link" data-tab="B-1">BUTTON B</li>
<li class="tab-link" data-tab="C-1">BUTTON C</li>
</ul>
<div id="A-1" class="tab-content current">
content A
</div>
<div id="B-1" class="tab-content">
content B
</div>
<div id="C-1" class="tab-content">
content C
</div>
</div>
<!-- container -->


thanks!

Answer

That is because you select all accordions in the page.

You want to do something like this:

jQuery('ul.tabs li').click(function(){
    var tab_id = jQuery(this).attr('data-tab');

    jQuery(this).closest('.mytabcontainer').find('ul.tabs li').removeClass('current');
    jQuery(this).closest('.mytabcontainer').find('.tab-content').removeClass('current');

    jQuery(this).addClass('current');
    jQuery("#"+tab_id).addClass('current');
})
Comments