onscroll event executes only once

1.2k views Asked by At

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"});
    }
}
}

jsfiddle

2

There are 2 answers

0
Cymen On BEST ANSWER

The problem is onscroll is being assigned the result of running scrolls(viewportWidth) but what you really want is to give onscroll a function to run. If you want to pass viewportWidth, you could instead do:

window.onscroll = function() {
  scrolls(viewportWidth);
};

Your updated JSFiddle: https://jsfiddle.net/n8vms2js/6/

0
cernunnos On

You are attaching the result of the function to the onscroll event when you do it like this:

window.onscroll = scrolls(viewportWidth);

Instead you have to either attach the callable like so:

window.onscroll = scrolls;

and then adapt it to your needs by getting the viewport width inside the function, or alternatively use an anonimous function to call your scrolls function with the pre-calculated viewport width, like so:

window.onscroll = function () {scrolls(viewportWidth)};

Fiddles: