Shane Shane - 3 months ago 11
jQuery Question

.scroll() is only running once

I'm trying to create a small snippet for a sticky sidebar with jQuery. For some reason, the function inside of

.scroll()
is only running once instead of running at every scroll event. What could I be doing wrong?

var sticky = $('#sticky');
var staticSticky = $(sticky).offset().top;

$(window).scroll(moveEl(sticky, staticSticky));

function moveEl(element, staticElToTop){
if( $(window).scrollTop() >= staticElToTop ){
$(element).css('top', $(window).scrollTop() + 'px');
}
}


See here for the entire attempt: http://codepen.io/ExcellentSP/pen/GqZwVG

The code above is not fully functional. I'm just trying to get the scroll event to work properly before I continue.

Answer

You need to wrap content of your your moveEl method into the function (to be returned for $(window).scroll()) like this:

var sticky = $('#sticky');
var staticSticky = $(sticky).offset().top;

$(window).scroll(moveEl(sticky, staticSticky));

function moveEl(element, staticElToTop) {
  return function() {
    if( $(window).scrollTop() >= staticElToTop ){
        $(element).css('top', $(window).scrollTop() + 'px');
    }
  }
}

Explanation: The key difference is that you call a function and it returns undefined by default, so it equals to $(window).scroll(undefined). Since you actually called it, you see it's fired only once which is obvious.

As soon as you return a function within moveEl method, .scroll() gets a handler, so it becomes $(window).scroll(handler). So it will work now as expected.

Comments