I’ve got some jQuery which should only be firing when the window width is 768px and above, but is continuing to fire even when the window size is resized to below 768. However, on refresh of the page it does not fire, despite there being a continual check for when the window is resized.
Also, I was wondering if this was the best way to check for window size or whether clientWidth would be better (I’m setting this up mainly for mobile and small tablets).
var win = $(window);
resizeHandler();
win.resize(resizeHandler);
function resizeHandler() {
if (win.width() > 768) {
$(window).scroll(function(){
$(".ws-menu-list").stop().animate({"marginTop": ($(window).scrollTop()) + "px"}, "slow", "linear" );
});
}
}
So I’ve been told that the calls to the function have to appear under the function itself.
I’ve repositioned the function but the element still animates unless I refresh the page with the window width below 768.
var win = $(window);
function resizeHandler() {
if (win.width() > 768) {
$(window).scroll(function(){
$(".ws-menu-list").stop().animate({"marginTop": ($(window).scrollTop()) + "px"}, 600, "swing" );
});
}
}
resizeHandler();
win.resize(resizeHandler);
So I’ve had another look into this and it seems that the scroll function is ignoring the if statement it’s within and continuing to fire regardless. I tested this by carrying out the following using the Console Log.
function resizeHandler() {
console.log("window resized");
if ($(window).width() > 768) {
console.log("window bigger than 768");
$(window).scroll(function(){
console.log("scrolling");
});
}
}
resizeHandler();
$(window).resize(resizeHandler);
However, I can’t see why the scroll wouldn’t be adhering to the if statement surrounding it?
The reason for this is that once you’ve attached a handler to the scroll event it’s set for the lifetime of the page, so even if the page is resized to below 768px it’ll continue to fire when the window is scrolled.
What you could is add an else clause to remove the scroll handler when the window size drops below 768.