I am adding an event listener in an `onFormLoad`:

Jason Wood:
I am adding an event listener in an onFormLoad:

window.addEventListener('scroll', function() {
  model.ui.headerScrolled = window.scrollY > 85
});

How would I clear this when the user navigates away from that page? Looking for something like onFormUnload


Rishad Alam:
Hi Jason, I can take a look at this.


Rishad Alam:

vueapp.$router.beforeEach((to, from, next) => {
    if (from.path === '/elements') { //path of the page exiting from 

       //function when leaving page
    }

});

Rishad Alam:
replace ‘/elements’ to the path of the your page. add a function to remove the event listener - window.removeEventListener(‘scroll’, handleScroll); handleScroll can contain the function that is to be used and removed


Rishad Alam:
This would go on to your onformload function


Jason Wood:
What should handleScroll be replaced with?


Jason Wood:
Here’s what I have right now but handleScroll is undefined.

window.addEventListener('scroll', function() {
  model.ui.headerScrolled = window.scrollY > 85
});
vueapp.$router.beforeEach((to, from, next) => {
  if (from.path === '/apply') {
    window.removeEventListener('scroll',handleScroll);       
  }
});

Rishad Alam:
function() {
model.ui.headerScrolled = window.scrollY > 85
} should be handle scroll


Jason Wood:
Here is the final solution. Moved the event listener function into its own separate function so it could be referenced in both addEventListener() and removeEventListener, and also add next() at the end:

function headerScroll() {
    model.ui.headerScrolled = window.scrollY > 85
}

window.addEventListener('scroll', headerScroll);

vueapp.$router.beforeEach((to, from, next) => {
    if (from.path === '/apply') { //path of the page exiting from 
       //function when leaving page
       window.removeEventListener('scroll', headerScroll);
    }
    next();
});

For your example, you’re using a scroll. So, you can attach the event listener to an object that’s within the DOM that’s within that page. When that page gets replaced, so does the DOM element and thus you don’t need to remove it. This will not work if you are attaching it to something that is not changing when you navigate from page to page mind you.