ToniStark
ToniStark

Reputation: 11

Target clicked element only

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/

Upvotes: 0

Views: 405

Answers (2)

Pape
Pape

Reputation: 291

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/

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

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.

Upvotes: 3

Related Questions