ExcellentSP
ExcellentSP

Reputation: 1619

.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.

Upvotes: 0

Views: 59

Answers (2)

oleh.meleshko
oleh.meleshko

Reputation: 4795

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.

Upvotes: 1

Gerald Chablowski
Gerald Chablowski

Reputation: 472

In doing that $(window).scroll(moveEl(sticky, staticSticky));, you ask to javascript to execute the function. You don't pass its reference.

 $(window).scroll(function(){ 
   moveEl(sticky, staticSticky);
 });

Upvotes: 0

Related Questions