jQuery add and remove $(window).scroll(function()?

Dee picture Dee · Nov 29, 2010 · Viewed 51.9k times · Source

How can I remove and then add the $(window).scroll? I need to store a variable and reuse it after some event.

// here i store my var
$(window).scroll(function(){
    myScroll = $(window).scrollTop()  
});

$("#itemUnbind").click(function(){
    // here i need to remove the listener        
});

$("#itemBind").click(function(){
    // here i need to add listener again     
});

Thank you.

Answer

Andy E picture Andy E · Nov 29, 2010

You need to store the function in a variable and then use off to remove it:

var scrollHandler = function(){
    myScroll = $(window).scrollTop();
}

$("#itemBind").click(function(){
    $(window).scroll(scrollHandler);
}).click(); // .click() will execute this handler immediately

$("#itemUnbind").click(function(){
    $(window).off("scroll", scrollHandler);
});