Add and Remove event listener javascript with example

Add and Remove event listener javascript with example

Add and Remove event listener with javascript is very simple. First, you need to create your function with your business logics.

We have taken an example of stop and start scrolling logic.

var previousScrollTop = 0;
function scrollEvents(){
    window.scrollTo(previousScrollTop,0);
    previousScrollTop = window.pageXOffset;
}

This example also covered your problem of Enable and Disable scroll with event listener javascript.

So now create your function to add an event, like this:

function addEvent(){
    previousScrollTop = window.pageXOffset;
    window.addEventListener('scroll', scrollEvents);
}

After this you need to add, remove event function:

Loading...
function removeEvent(){
    window.removeEventListener('scroll', scrollEvents);
}

Now, you need to call these functions according to your requirement.

//for add event
addEvent()
//for remeve event
removeEvent()

Related posts

Write a comment