Nuxt.js - Struggling to Remove Event Listener

I am currently utilizing nuxt.js and have implemented a scroller that scrolls and stops at a specific point on my page.

However, when I navigate to the next page, the method is still searching for the element with $ref=nav which no longer exists, resulting in an error message stating

Cannot read property 'getBoundingClientRect' of undefined

Although I can add the eventListener, I am facing difficulties in removing the eventListener.

Event Listener

mounted(){
   window.addEventListener('scroll', this.stickyScroll);
},
beforeDestroy(){
   window.removeEventListener('scroll', this.stickyScroll);
}

Scroller Function

stickyScroll(){
   window.document.onscroll = () => {
        let navBar = this.$refs.nav;
        let navBarXPosition = navBar.getBoundingClientRect().x;
        let navScrollSpy = this.$refs.navScrollSpy;
        let navScrollSpyXPosition = navScrollSpy.getBoundingClientRect().bottom;
        if(window.scrollY > navBarXPosition && navScrollSpyXPosition > 25){
             this.active = true;
         } else {
             this.active = false;
         }
    }
 },

Answer №1

window.document.onscroll = fn is essentially the same as

window.addEventListener('scroll', fn)
, meaning that stickyScroll() introduces a new event listener for each scroll event.

The solution involves eliminating the assignment of window.document.onscroll in order to incorporate the content of the arrow function into stickyScroll, which enables proper removal of the handler:

stickyScroll() {
  let navBar = this.$refs.nav;
  let navBarXPosition = navBar.getBoundingClientRect().x;
  let navScrollSpy = this.$refs.navScrollSpy;
  let navScrollSpyXPosition = navScrollSpy.getBoundingClientRect().bottom;
  if (window.scrollY > navBarXPosition && navScrollSpyXPosition > 25) {
    this.active = true;
  } else {
    this.active = false;
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can you explain the distinctions among “assert”, “expect”, and “should” in the Chai framework?

Can you explain the variations between assert, expect, and should? How do you know when to utilize each one? assert.equal(3, '3', '== turns values into strings'); var foo = 'bar'; expect(foo).to.equal('bar' ...

Error message: The attempted import failed because ' is not exported from the module

I am facing an issue with resolving my problem. In a file named lama.d.ts, I have declared a class using the following code: export declare class lama { // code here } After that, I tried to import this class in another file within the same folder ...

PHP: Dynamically update div content upon submission

I am attempting to update the "refresh" div after clicking the Submit button and also at regular intervals of 5 seconds. Despite looking through various resources, I have not been able to find a solution that meets my requirements. <script src="h ...

Issues with displaying images in Fancybox

I've integrated FancyBox into my website, but I'm experiencing a minor issue. While the FancyBox works perfectly in Dreamweaver, it seems to malfunction in various browsers. As someone who is not well-versed in programming, I'm struggling t ...

Is there a way to import a module generated by typescript using its name directly in JavaScript?

I am trying to bring a function from a typescript-generated module into the global namespace of JavaScript. The typescript module I have is called foo.ts: export const fooFn = (): string => { return "hello"; }; Below is the structure of my HTML file ...

Display a pleasant alert message when the file is not recognized as an image during the loading

Is there someone who can assist me? I have attempted multiple times but without success. How can I display a sweet alert when a file is selected that is not an image? <input type ="file" /> ...

Implement a fadeout effect by using a timeout function that adds a class to the div element in

I implemented a loader on my webpage that animates for 3 seconds before a function kicks in to modify the styles and make it invisible. I am looking to add a fadeout effect when the 'waa' style is applied to the 'load' div. setTimeou ...

Make changes to the HTML file by directly using Jquery or JavaScript

Allow me to elaborate on my current objective. I have an HTML file that requires direct content updates. Specifically, I am working with elements sharing the 'id=test'. My goal is to dynamically update all elements with unique IDs such as ' ...

Scroll Bar Menu (User-Controlled)

I'm looking for any libraries out there that can replicate or provide a similar horizontal scrolling menu to that of espn.com's homepage. I'm relatively new to jquery and feeling a bit lost on where to begin. I did some searching on Google, ...

Generate a unique sequence not functioning

I'm attempting to generate a unique string composed of random characters, similar to the example found at this source. $(document).ready(function(){ $('#randomize').click(function() { var str = ""; var possibleChars = "michaeljo ...

Interactive jQuery element featuring an image gallery displayed within a translucent black overlay on a webpage

My goal is to add a jQuery popup with an image that appears automatically when a website loads. I envision the popup creating a black transparent overlay, similar to this example. While setting up the basic popup was straightforward, integrating the image ...

Ajax implementation for handling URL action parameters

I am currently facing challenges in passing data from a view to a controller using parameters. My goal is to pass these parameters when I select a row from a table and click on a button that triggers the ShowTasks() function. Here is the C# controller cod ...

Rejuvenating a template generated on the server in AngularJS

I have a specific partial which is a report - simply a static list of names and dates designed for viewing and printing purposes. For efficiency reasons, the report is rendered server-side, so when a report request is made, my API responds with HTML rathe ...

Is it possible to use conditional logic on child elements in formkit?

I am a bit confused about how this process functions. Currently, I am utilizing schema to create an address auto complete configuration. My goal is to have the option to display or hide the fields for manual input. This is the current appearance of the ...

Incorporate jQuery to add numbering to rows along with input fields

I am trying to implement automatic numbering on the first column. Is there a way to increment the number by 1 every time the Submit button is pressed? jQuery: $(document).ready(function () { $("#btn-add").click(function () { va ...

What is the best way to extract data from the JSON response obtained from the Facebook Graph API in a Node

I am struggling to parse a JSON file in order to extract specific data, particularly the latest picture. How can I achieve this using Node.js and the Facebook Graph API? Below is the snippet of code I currently have: var params = { hostname: ' ...

Utilize React to showcase all stored items in localStorage in a Material UI List

I have a storage system with multiple items stored in it. I am looking to retrieve all of them and showcase them using a <ListItem> from Material UI. This is my current code snippet: function saveItem(key, value) { localStorage.setItem(key, value) ...

Using Discord.js to filter messages that start with a specific phrase and finding a solution for handling DiscordAPIError when using bulk

This is the code I am currently using. Shout out to @André Dion for the assistance. if (message.channel.type == 'text') { message.channel.fetchMessages().then(messages => { const botMessages = messages.filter(msg => msg.auth ...

When working with React, encountering a "TypeError: is not a function" message from a function prop can

I am a beginner with React and I'm attempting to pass a function as a prop to a child component. In this scenario, the parent component looks like this: const [gameStarted, setGameStarted] = useState(false); const [gameSettings, setGameSettings] = use ...

Having trouble with my AJAX request and can't figure out why. Anyone available to take a look and help out?

I have successfully implemented this AJAX script on various pages in the past without any issues. <script type="text/javascript" src="jquery-1.4.2.min.js"></script> <script type="text/javascript" src="jquery.validate.min.js"></script& ...