Home > Enterprise >  Add class again only if it previously existed
Add class again only if it previously existed

Time:09-07

I added a class "fixed" to the html tag, but only on some pages on my website (where I want to add position: fixed to block the scroll). When I open the hamburger menu, I want that class removed so the user can scroll through the navigation. I did it this way:

elmHamburger.addEventListener('click', () => {

  if (overlay.isOpened === true) {
    elmHamburger.classList.add('is-opened-navi', 'is-active');
    if ($('html').hasClass('fixed')) {
      $('html').removeClass('fixed');
    }
  } else {
    elmHamburger.classList.remove('is-opened-navi', 'is-active');
    // how to add it back here?
  }
  
});

When I close the hamburger menu, I want to add the class back, but only to the pages that previously had it, not to all of them. How to do that?

CodePudding user response:

maybe like this:

elmHamburger.addEventListener('click', () => {

  if (overlay.isOpened === true) {
    elmHamburger.classList.add('is-opened-navi', 'is-active');
    if ($('html').hasClass('fixed')) {
       $('html').removeClass('fixed');
       $('html').addClass('tmp-fixed');//add temp class
    }
  } else {
    elmHamburger.classList.remove('is-opened-navi', 'is-active');
    if ($('html').hasClass('tmp-fixed')) { 
       $('html').addClass('fixed');
       $('html').removeClass('tmp-fixed');
    }
  }
  
});

  • Related