Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

if window width less than X, do something if overpasses X on resize

I’m trying to add a rule that goes as: If the window width is less than 991 and resizes to something more or equal to 992, then do something.

I want to remove the class ‘opened’ from a megamenu only once if the screen is resized from mobile/tablet view (less than 991) to desktop view (more or equal to 992). But if the screen is already more than 992, do nothing.

All I can come up with are the resizes rules, but these keep applying every time I resize

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

if ($(window).width() >= 992) {
   $('.megamenu').removeClass('opened');
}

>Solution :

I am not 100% sure of your logic, but you can remove whatever elements from this that does not meet your specs. You can add the load event if you want to run this when the page loads too

let wasMobile = false;
let actionTaken = false; // to test if only once
let resizeTimeout;

$(window).on('resize', function() {
  clearTimeout(resizeTimeout); // debounce to not trigger for all resize events

  resizeTimeout = setTimeout(function() {
    const currentWidth = $(window).width();

    if (currentWidth >= 992 && wasMobile && !actionTaken) {
      // Perform the action only once when resizing from mobile/tablet to desktop
      $('.megamenu').removeClass('opened');
      wasMobile = false; // Update the state
      actionTaken = true; // Mark the action as taken
    } else if (currentWidth < 992) {
      // Update the state if in mobile/tablet view
      wasMobile = true;
      actionTaken = false; // Reset the flag when going back to mobile/tablet
    }
  }, 100); // 100ms debounce delay
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading