Reputation: 85
I have added a scroll event to the window using the below code.
window.onscroll=function () {
How to unbind this scroll event added to the window only by using Javascript?
Upvotes: 1
Views: 3257
Reputation: 452
The answer from VRFP is slightly incorrect. The event listeners should be added and removed with 'scroll'
as the event as follows:
window.addEventListener('scroll', myFunction, false);
window.removeEventListener('scroll', myFunction, false);
also, the function can be either an expression or declaration, it doesn't matter. Just be aware of function hoisting.
Function expression:
var myFunction = function() {
/* do something here */
};
Function declaration:
function myFunction() {
/* do something here */
};
Upvotes: 5
Reputation: 3118
Use
var myFunction = function (event) {
/* do something here */
};
window.addEventListener('onscroll', myFunction, false )
window.removeEventListener('onscroll', myFunction, false)
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener
Upvotes: 2