Customizing scrollBehavior in Nuxt.js for a specific route transition

Within my Nuxt page, I have implemented functionality to scroll to the top with every router change, as defined in the nuxt.config.js file:

scrollBehavior (to, from, savedPosition) {
  return ({ x: 0, y: 0 })
}

However, there is a unique navigation link labeled "Contact" that does not direct users to a separate contact page. Instead, it should navigate to the footer section where the contact information is displayed on every page. To achieve this, I added a standard anchor link to target the #contact section within the footer:

<a class="Submenu__link Submenu__link--contact" href="#contact">
    Contact
</a>

Unfortunately, clicking this special link triggers a route change, causing the page to scroll back to the top. In an attempt to resolve this issue, I tried creating a function to set the scrollTop property. However, this resulted in a flickering effect where the page would briefly scroll down before snapping back to the top:

<li class="Submenu__item">
    <a @click="closeNavAndScroll" class="Submenu__link Submenu__link--contact" href="#contact">
        Contact
    </a>
</li>

I also defined a method for handling the click event (which successfully closes the navigation menu):

closeNavAndScroll () {
    this.closeNavMenu()
    window.scrollTop(400)
}

Upon further research, I visited the following link for more information: https://nuxtjs.org/api/configuration-router#scrollBehavior

From what I gathered, the scrollBehavior configuration applies to all routes, and there doesn't seem to be a specific solution for preserving scroll position when navigating to anchors like #contact. Any suggestions or guidance on how to address this issue would be greatly appreciated.

Thank you!

Cheers

Answer №1

Construct the #contact anchor just like before, but adjust the scrolling functionality to accommodate it:

scrollAdjustment (target, previous, storedLocation) {
  if (target.hash) {
    return {position: target.hash}
  } else {
    return {horizontal: 0, vertical: 0}
  }
}

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

Unable to inject dependencies into Karma testing framework

I am facing the challenge of injecting the $urlRouterProvider into my tests, but I persistently encounter the unknown provider issue. My setup involves ui.router and the testing of directives, requiring access to these providers to prevent test failures... ...

Regular expression for ensuring the validity of a currency amount with a specific minimum value

Currently, I have a regular expression that successfully validates money. ^\d{1,3}(,\d{3})*$ However, I now need to modify it to include a minimum amount requirement of 20,000. Can someone assist me with this adjustment? Fiddle: fiddle updated ...

Employing square bracket notation based on the input data

I'm currently in the process of enhancing some code within my library, but I've encountered a perplexing issue with bracket notation not functioning as expected when attempting to call an imported class. The parameter type expects a camelCased s ...

Content within a Row of a Data Table

Hello! I am just starting to learn JavaScript and jQuery. Can you help me with an issue I am experiencing? Basically, I have a table and I need to identify which tr contains a td with the text "Weekly", "Daily", or "Monthly". Once I locate that specific t ...

After utilizing Geolocation, the input fields in Ionic/Angular JS are failing to update accurately

Currently, I am in the process of developing a new App using Ionic and Angular JS. Specifically, in one of the app tabs, I am utilizing geolocation to populate four fields (street name, street number, latitude, and longitude). Below is the snippet of my c ...

Disabling the scrollbar in Selenium screenshots

When using Chromedriver to capture screenshots of webpages, my code effectively does the job. However, I am now facing an issue with removing the unsightly scrollbars from the image. Is it feasible to inject CSS into the webpage in order to achieve this? W ...

A URL that quickly updates live content from a backend script

As a beginner, I am seeking guidance as to where to start on my journey of learning. I need assistance in creating a script that can efficiently fit within a small URI space and constantly updates itself with information from a server script. My target bro ...

Limiting the quantity in SimpleCart (js)

Currently, I am working on a WordPress website where I am using simpleCart(js) to add a shopping cart feature. I sell unique articles and do not require users to add more than one article to their cart. My main concern is how to prevent users from adding ...

I need clarification on some basic concepts about ajax - Can you help?

Could someone please assist me in clarifying a concept? Currently, I am utilizing the colorbox plugin to load an external html snippet (which is functioning correctly). However, my jquery selectors are unable to detect the newly loaded html. Is this the co ...

Retrieving the value of a local object property by using a string identifier

How can I retrieve the value of a property from a local object variable using its fully qualified variable name? function foo() { var obj = { prop: "val" } var valueStr = "obj.prop"; var value = // code here that gets value using ...

I encountered an undefined type error while converting my code to an Object using JavaScript AJAX

I am puzzled by the TypeError (this.req is undefined) that I am encountering on this line of code: if (this.req.readyState === 4) { function RequestCORS(url) { this.url = "http://crossorigin.me/" + url; this.req = new XMLHttpRequest(); } RequestCORS ...

What is the best way to implement multiple filters on the data of a Vue component?

I am facing a challenge in implementing multiple filters in a component. For instance, users should be able to choose a category and have the results filtered accordingly. Moreover, with a search filter already in place, I am looking for a way to combine i ...

What is the method for showcasing a specific value using a filter?

In my app, I have the following data: birthdayGreetings:Array<any> = [ { name: 'John', date: new Date(1994, 3, 19), greeting: 'Happy Birthday, John! Good luck!', displayName: false } ]; I ...

Update the page by selecting the refresh option from the drop-down menu

In my script, I have different views showing information retrieved from a database. One view displays the quantity of a product sold each month, another shows sales, the third presents profits, and the last exhibits calculated percentages using sales and p ...

Determine the frequency of duplicate elements in an array and arrange them in descending order based on their frequency

After making an API call, my array is populated with values like this: ["9777", "9777", "2.4", "9777", "2.4", "2.4", "9777", "2.4", "2.4", "9777", "9777", "2.4", "2.4", "2.4"] My goal is to count the occurrences of each item in the array and then sort th ...

A JointJS element with an HTML button that reveals a form when clicked

How do I bind data to a cell and send it to the server using the toJSon() method when displaying a form on the addDetail button inside this element? // Custom view created for displaying an HTML div above the element. // ---------------------------------- ...

What is the best way to eliminate all occurrences of a specific element within an array?

I'm currently facing an issue with my code - it's supposed to remove all instances of a certain item from an array, but it's not working as expected. Can anyone help me identify what I'm doing wrong? let nums = [1, 90, 90, 1123, 90, ...

Generate dynamic Bootstrap Carousel slides with unique hashtag URLs

I've been attempting to connect to various slides within a bootstrap carousel from a different page but have had no success. Here is an example of what I'm trying to achieve: <a href="services#slide2">Link to Slide 2</a> For refere ...

Retrieve the `access_token` attribute from local storage

I have stored the token in local storage using: localStorage.setItem('token', JSON.stringify(res.data)). Now, I am attempting to retrieve the access_token property. JSON.parse(localStorage.getItem(token['access_token'])) An error is o ...

When trying to click on an HTMLTableRowElement, an Uncaught ReferenceError occurs in React.js and jQuery, stating that the function is

When I was working on my web app, I encountered an issue while trying to create a table. Upon clicking on it, I received an error message: Uncaught ReferenceError: (function) is not defined at HTMLTableRowElement.onclick Here is the code for the table: $( ...