What is the best way to remove an event binding before navigating to a different page in NUXTjs?

I wrote this code all on one page and it works perfectly. However, I am unsure how to unbind this event when transitioning to another page.

 private mounted () {
      if (process.browser) {
        const banner:any = document.querySelector('.banner img')
        document.addEventListener('scroll', () => {
          const offsetTop = window.scrollY
          const INTOR_HEIGHT = document.querySelector('.intro-text').offsetHeight
          if (offsetTop < INTOR_HEIGHT) {
            banner.style.top = offsetTop + 'px'
          }
        })
      }
    }

Whenever I navigate to a different page from this one, an error is thrown:

javascript Uncaught TypeError: Cannot read property 'offsetHeight' of null at HTMLDocument.eval

Answer №1

hehe, With VUE.js Instance Lifecycle Hooks in nuxt.js, you can achieve some cool effects like this:

private smoothSlider () {
      const bannerElement:any = document.querySelector('.banner img')
      const scrollOffset = window.scrollY
      const introHeight:any = document.querySelector('.intro-text').offsetHeight
      if (scrollOffset < introHeight) {
        bannerElement.style.top = scrollOffset + 'px'
      }
    }

private mounted () {
      if (process.browser) {
        document.addEventListener('scroll', this.smoothSlider)
      }
    }

private beforeDestroy () {
      document.removeEventListener('scroll', this.smoothSlider)
    }

The key is to bind a global event in the mounted hook and unbind it in the beforeDestroy hook.

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

Adding an item to a collection using NgRx

I am working with a state that has a specific structure. It consists of a list of Workouts, and each Workout contains a list of exercises associated with it. I have two main objectives: To add new exercises to a particular workout from the existing list o ...

Can someone explain the significance of '{}' within the function shown below?

I've been able to grasp most of this code, but I'm unsure about "{}". Can anyone clarify its meaning? var Toggle = function(section, expand) { this.section = section || {}; this.expand = expand | ...

Implementing a try-catch-finally block in Javascript to handle errors during JSON parsing appears to be ineffective

As someone relatively new to web scripting, I find the similarities between Java try-catch blocks and Javascript ones intriguing. However, my attempts at using them have yielded slightly different results than expected. Here is a snippet of code showcasing ...

What is the proper way to set up state with localStorage in Nuxt.js when using Universal Rendering?

Unique Situation In my unique setup, I have a specific flow that involves storing a token in localStorage, even though I know it's not the recommended practice. Every time my Nuxt App is launched, I need to retrieve the token from localStorage, valid ...

Can a Unicode character be overwritten using a specific method?

Is there a way to display a number on top of the unicode character '♤' without using images? I have over 200 ♤ symbols each with a unique number, and using images would take up too much space. The characters will need to be different sizes, a ...

How can I incorporate eventData when using .bind() for the "keydown" event type?

I want to achieve something like this: var keydownHandler = function (ev) { alert(ev.data.test); return false; } $(document).bind('keydown', {test: 'foo'}, keydownHandler); However, the .bind method doesn't seem to be wor ...

Utilizing AJAX POST requests from JavaScript to a Rails 4 controller while implementing Strong Parameters

As a newcomer to Rails, I am looking to insert song_id and title received from JavaScript via AJAX POST into a MySQL database. In my JavaScript file: var song_id = "23f4"; var title = "test"; $( document ).ready( function() { jQuery.ajax({ ...

What is the process of specifying that an Angular directive must act as a child directive within a particular directive in Angular?

I am currently developing a directive for AngularJS. How can I specifically configure it to require being a child of directiveA? For instance, consider the following example: <my-modal> <m-header>Header</m-header> </my-modal> ...

Issue with Vue 3: Button components fail to update upon modification of second dropdown menu

As a newcomer to Vue, I've encountered a challenging issue that I'm struggling to solve. Despite making significant progress on a complex project, I find myself perplexed by what should be a simple feature... A Brief Background/Overview: The pro ...

The list countdown for loop only appears in the initial iteration

Hey there, I'm currently facing an issue with duplicating my JavaScript countdowns and displaying images of cards on each loop iteration. Strangely, the countdown only appears in the first instance even though it's within the loop. I'm seeki ...

The pre tag does not have any effect when added after the onload event

I have been experimenting with a jQuery plugin for drawing arrows, detailed in this article. When using the plugin, this code is transformed: <pre class="arrows-and-boxes"> (Src) > (Target) </pre> into this format: Src --> Target The ...

Fixing the version mismatch error when attempting to create a Vue project

While attempting to create a vue project using vue create shop, I keep encountering the following error message: Error: Vue packages version mismatch: - <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f5838090b5c7dbc3dbc4c4" ...

Having trouble getting the form to submit with jQuery's submitHandler

I am in the process of converting a contact form to AJAX so that I can utilize the success function. Currently, I am encountering an issue where the code is halting at the submitHandler section due to it being undefined. Can anyone identify why my submitHa ...

Extract and loop through JSON data containing various headers

Having no issues iterating through a simple JSON loop, however, the API I am currently utilizing returns a response with multiple headers. Despite my efforts in various methods to access the results objects, I still face some challenges. The response struc ...

Using Vue.js to transmit information within the same component

I'm relatively new to working with Vue.js and I have a question about passing data. Specifically, I want to pass the data stored in profile, which can be found within the created() method, into: <span v-if="isLoggedIn">{{this.profile.username}} ...

How can you locate the position of a selector within a parent or set using jQuery

Could someone please help me determine the position of the current selector within its parent using jQuery? I need this information in order to effectively use the .insertAfter() and .insertBefore() methods to rearrange elements within their nested structu ...

6 Steps to Extract Data from a POST Request Using JavaScript

I have a form that includes a text field and a select field. When the form is submitted, I am posting it. Can someone guide me on how to extract the form data on the server using JavaScript? <form id="createGameForm" action="/createGame" method="post" ...

Is there a simple method to submit to a URL without relying on ajax?

When it comes to using jQuery, the $.ajax() function is typically used for POST requests to a URL. However, in my particular situation, I am unable to use this function. I need the client to send a POST request to a URL and have the server redirect the use ...

Material UI filterSelectedOptions not functioning properly on initial search with multiple autocomplete

When I utilize the filterSelectedOptions prop in my autocomplete feature, it functions as intended when using a pre-defined chip. Check out image1 for an example: image1 However, when a brand new typed option is entered, it ends up duplicating multiple ti ...

Retrieve the Latest Information from the Asp.Table

My table setup is as follows: <asp:Table ID="model" runat='server'> <asp:TableRow> <asp:TableHeaderCell class="col-xs-2"> Name </asp:TableHeaderCell> <asp:TableHeaderCell class="col- ...