Home > front end >  Can't get "if hasclass addclass" to work (jQuery)
Can't get "if hasclass addclass" to work (jQuery)

Time:12-12

I am working on a wordpress website and I want to add a class to the body to prevent it from scrolling when the mobile menu is open.

I'm quite new when it comes to jQuery but after doing some reading I thought I had something that should be working, but it doesn't seem to and I can't figure out why. I'm also using bootstrap and their collapse tool. When the menu is open it adds the class 'show' to one of my divs and I'm trying to use that condition to add a class to the body.

Here is the jQuery code I added :

(function($) {
  $(document).ready(function() {
  if ( $('#collapseMenu').hasClass('show') ) {
    $('document.body').addClass('bodyblock'); }
  })
})(jQuery);

And the CSS : .bodyblock { position : fixed; }

A jsfiddle with an approximation of what seems relevant to me here : http://jsfiddle.net/bot03eur/

I usually try to figure it out by myself or find a workaround but I'm at a loss here, any help would be greatly appreciated !

CodePudding user response:

jQuery only need 1 function to make it work.

And your selector is not good, you need only $('body') to target it.

$(document).ready(function() {
  if ($('#collapseMenu').hasClass('show')) {
    $('body').addClass('bodyblock'); 
    console.log("Class bodyblock added to the body tag");
  }
})
.bodyblock {
  background-color: grey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
  <div id="collapseMenu" ></div>
</body>

  • Related