Home > Net >  How to condition a class
How to condition a class

Time:11-09

I'm new to JS and I want to know if there's any possible way to condition a class

I'll put you in context. I'm trying to disable the scroll-bar for my mobile navbar and I got this so far:

<style>
  .no-scroll {
    overflow: hidden;
  }
</style>

<script>
  $('.checkbtn').on('click', function() {
    $('body').toggleClass('no-scroll');
  });
  if (/* I NEED YOUR HELP HERE */) {
    $('.checkbtn').on('click', function() {
      $('body').removeClass('no-scroll');
    });
  }
</script>

Am I doing fine so far? Anyway, my question is how can I tell IF that 'body' has to have no-scroll class for it to work

Edit: My hamburger navbar icon class is called ".checkbtn"

CodePudding user response:

you can use hasClass method

for example

if($('body').hasClass('no-scroll'){
  // your code
}

CodePudding user response:

The only thing you need for the button to toggle that class on body is:

<script>
  document
    .querySelector('.checkbtn') // <button> or null if not found
    .addEventListener('click', () => document.body.classList.toggle('no-scroll'));
</script>

To be able to have multiple buttons, and not have an error when there are no buttons with the class, you can instead loop over found elements as follows:

<script>
  const listener = () => document.body.classList.toggle('no-scroll');
  for (const btn of document.querySelectorAll('.checkbtn'))
    btn.addEventListener('click', listener);
</script>
  • Related