Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 266
Dee Avatar asked Nov 29 '10 17:11

Dee


People also ask

Why scroll function is not working?

When the mouse won't scroll, there are two issues that most commonly cause it. The first is dust and dirt causing mechanical issues with the mouse wheel. The second is low battery issues on wireless mice.

How can use scroll event in jQuery?

jQuery scroll() MethodThe scroll event occurs when the user scrolls in the specified element. The scroll event works for all scrollable elements and the window object (browser window). The scroll() method triggers the scroll event, or attaches a function to run when a scroll event occurs.

How get scroll count in jQuery?

$(document). ready(function(){ var scrollPos = 0; var Counter = 0; $(window). scroll(function(){ var scrollPosCur = $(this). scrollTop(); if (scrollPosCur > scrollPos) { Counter -= 1; } else { Counter += 1; } scrollPos = scrollPosCur; }); });


1 Answers

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); }); 
like image 139
Andy E Avatar answered Sep 22 '22 19:09

Andy E