37

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.

user113716
  • 318,772
  • 63
  • 451
  • 440
Dee
  • 3,185
  • 10
  • 35
  • 39

1 Answers1

80

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);
});
Andy E
  • 338,112
  • 86
  • 474
  • 445
  • 1
    @Dee - if this works for you, please mark it as the answer by clicking on the "tick" icon. – Fenton Feb 03 '11 at 14:00
  • 3
    I think this should be: $("#itemUnbind").click(function(){ $(window).unbind("scroll", scrollHandler); }); – Jack Allan Mar 08 '13 at 15:28
  • 1
    @JackAllan: you'd think somebody else might have noticed that in the past 2 years! While the old solution would have worked for most people, it would have unbound all handlers for the event. – Andy E Mar 08 '13 at 15:50
  • you should consider editing your answer to reflect that. – gdbj Jan 24 '16 at 17:34
  • 1
    @gdbj: I did, almost 3 years ago. The difference is I used `off` instead of `unbind` (the latter is deprecated). – Andy E Jan 25 '16 at 09:38
  • for me the `.off` is not work - I try the `unbind` and works – Aristos Sep 06 '17 at 14:26