Coder95
Coder95

Reputation: 93

JQuery - Add and remove class on click

$('.toggle-button').on('click', function() {
    $('body').addClass('changeCursor');
  });

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

Hey guys I need to add class on body and should remove when again click on it. I have attached my code above. But it's not working please go through for more clarity. Thanks :)

Upvotes: 1

Views: 871

Answers (2)

oma
oma

Reputation: 1894

Check if your body has the class, if not add it, else remove it.

$('.toggle-button').on('click', function() {
    if($('body').hasClass('changeCursor')) {
        $('body').removeClass('changeCursor');
    } else {
        $('body').addClass('changeCursor');
    }
});

Upvotes: -1

Luke Walker
Luke Walker

Reputation: 501

You can use toggleClass()

Example:

$('.toggle-button').on('click', function() {
    $('body').toggleClass('changeCursor');
});

Docs: http://api.jquery.com/toggle/

Upvotes: 7

Related Questions