0

I've made a simple switch button. Classes are changing well but when I have multiple instances of this button it doesn't keep the original selection.

Thanks in advance

HTML

<ul class="button-switch"> <li><a href="#" class='active'>Spider-Man</a></li> <li><a href="#">Iron Man</a></li> <li><a href="#">Thor</a></li> <li><a href="#">Hulk</a></li> </ul> 

JQUERY

$('.button-switch li a').click(function(e) { e.preventDefault(); $('.button-switch li a').removeClass('active'); $(this).addClass('active'); }); 

JS fiddle example https://jsfiddle.net/t1gsp90j/1/

0

2 Answers 2

3

You need to make the selector which removes the class contextual to the ul which contains the li that was clicked. Try this:

$('.button-switch li a').click(function (e) { e.preventDefault(); $('li a', $(this).closest('ul')).removeClass('active'); $(this).addClass('active'); }); 

Updated fiddle

$(this).closest('ul').find('li a').removeClass('active'); would also have the same effect.

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome ! Thanks Rory
0

Your onClick event removes the class "active" from all elements on the page that match ".button-switch li a", so the current behaviour is to be expected.

What you want is to only remove "active" from siblings of the clicked element:

$('.button-switch li a').click(function(e) { e.preventDefault(); var target = $(e.target); var parentUl = target.closest('.button-switch'); // Find all links inside the current parent ul element. parentUl.find('li a').removeClass('active'); target.addClass('active'); }); 

Further on i would suggest to rewrite the click event like this for improved performance

$('.button-switch').on('click', 'li a', function(e) { e.preventDefault(); var target = $(e.target); var parentUl = target.closest('.button-switch'); // Find all links inside the current parent ul element. parentUl.find('li a').removeClass('active'); target.addClass('active'); }); 

https://jsfiddle.net/Macavity/t1gsp90j/5/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.