Search code examples
jquerytwitter-bootstraponclickbackground-color

Class change of button via jquery is changed back, when clicking another button from same class


I want to change the color of the buttons on my white ('btn-secondary') pagination from bootstrap to yellow ('btn-warning'), when they are clicked. This works with my code below, but If I click the next button on the same pagination, the previously clicked button turns to the previous color.

The HTML:

<button class="showAufgabe btn btn-secondary btn-sm">01</button>
<button class="showAufgabe btn btn-secondary btn-sm">02</button>
...
<button class="showAufgabe btn btn-secondary btn-sm">39</button>
<button class="showAufgabe btn btn-secondary btn-sm">40</button>

The jQuery:

$(document).ready(function() {
    var showAufgabe = $('.showAufgabe');
    $(document).on('click', showAufgabe, clickedAufgabe);

    function clickedAufgabe() {
        $(this).addClass('btn-warning').removeClass('btn-secondary');
    }
});

Thank you in advance! :-)

Here's a gif of how it looks: Simulation.gif

I want the first one to stay yellow!


Solution

  • When you are setting .showAufgabe to a variable, you are actually selecting all elements that share that same class name - in this case all buttons.

    var showAufgabe = $('.showAufgabe');
    

    Instead you could call $(this) when a button is clicked within your function. It would then toggle .btn-warning only on that specific button.

    $(".showAufgabe").on('click', function() {
      $(this).toggleClass('btn-warning');
    });
    .btn-warning {
      background-color: yellow;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button class="showAufgabe btn btn-secondary btn-sm">01</button>
    <button class="showAufgabe btn btn-secondary btn-sm">02</button>
    ...
    <button class="showAufgabe btn btn-secondary btn-sm">39</button>
    <button class="showAufgabe btn btn-secondary btn-sm">40</button>

    Side note: it may depend on your specific requirement, but you wouldn't have to remove the previous class, as .btn-warning appears further down in the bootstrap style sheet than .btn-secondary, applying it to the button class would overwrite the previous style applied via .btn-secondary.