Waleed Afridi
Waleed Afridi

Reputation: 107

JQuery add and remove class onclick

I wanted to show and remove css class when the button is clicked, i know there's a solution using toggleclass() but i want to add class using onClick function.

Here's the code

jQuery(document).ready(function(){
   jQuery(".main-header-menu-toggle").click(function () {
      jQuery("body").addClass('ast-main-header-nav-open');
   });
});

I want to add class to body, it worked when i click on the button but when i again close the button it doesn't remove the class.

Upvotes: 0

Views: 3982

Answers (2)

Mani
Mani

Reputation: 46

It does not remove because there is no code for remove class from body. Please use the above code as following:

jQuery(document).ready(function(){
   jQuery(".main-header-menu-toggle").click(function () {
      jQuery("body").toggleClass('ast-main-header-nav-open');
   });
});

By using toggleClass method, a class will be added on first click and will be removed when you again click on the button.

Try this with hasClass method if it is not working for Safari

jQuery(document).ready(function(){
 jQuery(".main-header-menu-toggle").click(function () {
  if(jQuery("body").hasClass('ast-main-header-nav-open')){
    jQuery("body").removeClass('ast-main-header-nav-open')
  }else{
    jQuery("body").addClass('ast-main-header-nav-open');
  }
 });
});
body {
  background-color:green;
  display:block;
  height:200px;
  width:200px;
}
body.ast-main-header-nav-open{
  background-color:red;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<a class="main-header-menu-toggle">Click me!</a>
</body>

Upvotes: 3

As the friends said above, you can do it in a simple way.

Deletion is triggered when the hasClass function returns true. When it returns to false, the insertion process is triggered. We have done this with the if condition.

$(function() {
  $(".main-header-menu-toggle").click(function() {
    ($('body').hasClass('ast-main-header-nav-open')) ? $('body').removeClass('ast-main-header-nav-open'): $('body').addClass('ast-main-header-nav-open')
  });
});
.ast-main-header-nav-open {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<a class="main-header-menu-toggle">Click</a>
</body>

Upvotes: 1

Related Questions