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
if ($(window).width() >= 992) {
$('.megamenu').removeClass('opened');
}
2
There is plenty of answers on internet about it, but here is some help :
When you write
if ($(window).width() >= 992) {
$('.megamenu').removeClass('opened');
}
your code is executed only once, when you load the page.
You should also listen to the resize
event to execute your function every time the window is resized.
$(window).on('resize load', function(){
if ($(window).width() >= 992) {
$('.megamenu').removeClass('opened');
}
});
Note that I also added the load
event in order to run the function on the page loaded event.
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
});
4