I'm using this code to get offset of an element in the page while scrolling but the scroll function is executed only once and alerts the viewportWidth then it stops at the 'off' variable
This is a simple example from the original script it's not just about setting the #menuIcon as fixed all the time
$(document).ready(function(){
document.body.style.overflow = "hidden";
var viewportWidth = $(window).innerWidth();
document.body.style.overflow = "";
window.onscroll = scrolls(viewportWidth);
});
function scrolls(viewportWidth){
alert(viewportWidth);
if(viewportWidth>100 && viewportWidth<=820){
alert('test');
var w = $(window);
var offset = $("#menuIcon").offset();
var off = offset.top-w.scrollTop();
if(off<='10'){
$("#menuIcon").css({"position":"fixed","top":"20px"});
}
}
}
The problem is
onscroll
is being assigned the result of runningscrolls(viewportWidth)
but what you really want is to giveonscroll
a function to run. If you want to passviewportWidth
, you could instead do:Your updated JSFiddle: https://jsfiddle.net/n8vms2js/6/