0

What is the best way to add and remove classes, clicking a button back and forth?

    $('button.hamburger').on('click', function(){
      $(this).addClass('is-active');
    });

    $('button.is-active').on('click', function(){
      $('button.is-active').removeClass('is-active');
    });

It doesn't remove .is-active class.

Do I need if statments to check whether the the element .hasClass()?

Tadas Stasiulionis
  • 1,316
  • 3
  • 16
  • 18

2 Answers2

5

You can use toggleClass() - Cheers.

$("button.hamburger").click(function(){
  $(this).toggleClass("is-active");
});
.is-active {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="hamburger">Click me...</button>
webta.st.ic
  • 4,781
  • 6
  • 48
  • 98
3

Since the active class is adding dynamically, you need to use delegate,

$(document).on('click', 'button.is-active', function() {
  $(this).removeClass('is-active');
});

Or you can simply use toggleClass(),

$('button.hamburger').on('click', function() {
  $(this).toggleClass('is-active');
});
Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53