I have a jQuery script which inserts and removes some CSS classes when certain conditions are met. It is used to enhance a sticky menu at the top of a web page.
While the code is bug-free, I cannot figure out how to add a condition that re-executes this same code when the browser window is resized. For instance, if the browser width is initially detected as 1366px, even if I resize it to say 800px, the code that should apply for $(window).width() <= 960
is not executed. If a refresh the page with the 800px width already set, everything works perfectly.
I tried several things with $(window).resize()
but nothing has worked so far.
The code I'm using for modifying the CSS is the following :
function updateContainer() {
$(window).scroll(function() {
if ( $(window).width() > 960 ) {
if( $(window).scrollTop() > 40 && $(document).height() - $(window).height() > 79 ) {
$(".site-header").addClass("site-header-scrolled");
} else if ($(window).scrollTop() <= 40) {
$(".site-header").removeClass("site-header-scrolled");
}
} else {
if( $(window).scrollTop() > 40 && $(document).height() - $(window).height() > 160 ) {
$(".title-area").hide(200);
$(".nav-menu").addClass("nav-menu-scrolled").hide(200);
if ( !$(".mobile-nav").length ) {
$(".title-area").before('<div class="mobile-nav"><p>Navigation ☰</p></div>');
} else {
return false;
}
$(".mobile-nav").click(function(){
$(".nav-menu").slideToggle(200);
});
} else if ($(window).scrollTop() <= 40) {
$(".title-area").show(200);
$(".nav-menu").removeClass("nav-menu-scrolled").show(200).removeAttr("style");
$(".mobile-nav").remove();
}
}
});
I have also wrapped this same code in :
$(document).ready(function() {
"use strict";
});
I'm not sure if it's absolutely necessary.
I tried the first two solutions found here : jQuery on window resize. While
$(document).ready(function () {
updateContainer();
$(window).resize(function() {
updateContainer();
});
});
}
kind of works for me, everything becomes buggy. Code for both cases (<= 960px and > 960px) is applied at the same time.
In advance, I thank you for your help !!