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?
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?
Share Improve this question edited Jan 26, 2021 at 17:45 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Sep 8, 2015 at 19:36 SareeshSareesh 851 silver badge9 bronze badges 2-
With
window.onscroll = function(){}
? – Kyll Commented Sep 8, 2015 at 19:38 - @Sareesh you should accept the answer of AdamJB – Jannie Theunissen Commented Oct 9, 2018 at 6:20
2 Answers
Reset to default 5The 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 */
};
Use
var myFunction = function (event) {
/* do something here */
};
window.addEventListener('onscroll', myFunction, false )
window.removeEventListener('onscroll', myFunction, false)
https://developer.mozilla/en-US/docs/Web/API/EventTarget/removeEventListener