Issue regarding navigation using nuxt-links to pages with hashtags/anchors

When it comes to my website navigation, I rely on nuxt-links a lot. Most of these links direct users to specific sections within the home page using hashes like:

<nuxt-link
  v-else
  class="text-link"
  :to="localePath('index') + #hash"
>

Everything works fine when I'm on the home page itself. However, things get tricky when I try to navigate from another page, such as /about, and click on a navbar nuxt-link. This results in a nuxt error message displaying "Cannot read property 'offsetTop' of null".

To make sure scrolling to anchored elements works even within the same site, I have configured my router in nuxt.config as follows:

  router: {
    scrollBehavior(to) {
      if (to.hash) {
        return window.scrollTo({ top: document.querySelector(to.hash).offsetTop + window.innerHeight, behavior: 'smooth' });
      }
      return window.scrollTo({ top: 0, behavior: 'smooth' });
      }
  },

I've tried various methods like 'hash' or '#hash' in the :to attribute, but nothing seems to work. Can someone please guide me on how to successfully navigate to a different page along with scrolling to a specific anchor?

Answer №1

If you're facing this issue, here's a quick fix for those using Nuxt-Link:

Instead of the non-functional

<nuxt-link to="#contact" >Contact</nuxt-link>
, try
<nuxt-link :to="{ path: '/',hash:'#contact'}">Contact</nuxt-link>

path refers to the destination page

hash specifies the scroll position

Hopefully, this solution proves useful to someone.

Answer №2

When dealing with subsections, I find that using getBoundingClientRect().top+window.scrollY is more effective:

if (to.hash) {
        let el = await findEl(to.hash)
        if ('scrollBehavior' in document.documentElement.style) {
          return window.scrollTo({ top: el.getBoundingClientRect().top+window.scrollY, behavior: 'smooth' })
        } else {
          return window.scrollTo(0, el.getBoundingClientRect().top+window.scrollY)
        }
      }

Answer №3

Although a bit delayed, I was able to successfully achieve this with the help of Sivuyile-TG-Magutywa

<nuxt-link :to="{ path: localePath('index'),hash:'#about'}">
          {{ $t("menu.about") }}
 </nuxt-link>

Here is the final result:

https://www.shrek.com/fr/about

Answer №4

I was hoping to associate a data ID with a link like this:

<div class="col" v-for="(item, index) in category.children.slice(0, 5)" :key="index">
<nuxt-link :to="{ path: localePath('/category/'+item.slug)}" target="_blank">

           

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

What is the most effective way to transfer a variable between two javascript files?

I am currently working on customizing the code from a github repository found at Github repo for integration with Google App Engine. However, I have encountered an issue when trying to pass a variable from /app.js to /books/crud.js. Although I have success ...

The Angular datepicker is failing to trigger the ng-change event

I've run into a snag with the datepicker and ng-change functionality. Oddly enough, the ng-change event isn't triggering when I manually select a date by clicking on it, but it works fine when I input a date manually. Take a look at my code snip ...

Is there a way to transfer a variable between elements using VueJs?

Is it possible to transfer variables between elements in VueJs? Vue Image ...

Is there a way to determine the number of clicks on something?

I'm attempting to track the number of times a click event occurs. What is the best method to achieve this? There are two elements present on the page and I need to monitor clicks on both of them. The pseudo-code I have in mind looks something like ...

What are some ways to address alignment problems that occur with input fields when the file name is lengthy?

When using input type="file", the alignment is not proper when the file name is long with multiple words... https://i.stack.imgur.com/52Yh5.png I would like it so that when the file name is long, it displays like this: From - New_InkDrops_HD_ ...

Optimal approach for reutilizing Javascript functions

After creating a simple quiz question using jQuery, involving show/hide, addClass, and tracking attempts, I am now considering how to replicate the same code for multiple questions. Would it be best practice to modify all variables in both HTML and jQuery, ...

Adding properties to Vue.js component in the script section without affecting rendering

How can I import component A with props and pass it to another component B for rendering? import MyComponent from '/MyComponent.vue' computed: { compnt: function () { var comp = MyComponent // How can I set props to MyC ...

Encountering an Error when Integrating Pusher (real-time data library) with Next.js: PusherRequestError - Unexpected status code 400

I encountered an issue while trying to integrate Pusher into my Next.js application due to Vercel's restriction on websockets in their serverless functions. The error message I keep receiving after running the program with Pusher is: error - unhandled ...

Creating a custom event for every reference within a Vuejs for loop

I'm working with a loop of data and have a modal for each iteration <div ref="vuemodal-{{loop.index}}"> Each modal is a bootstrap modal, and I want to bind an event to them that triggers whenever the modal is closed mounted(){ Obj ...

What is the best way to incorporate a sidebar menu in an HTML webpage?

I am interested in creating a sidebar menu for my website using either HTML, CSS, or JavaScript. The W3 Schools website has a side menu that I find appealing and would like to create something similar. ...

Require assistance with handling Ajax when a function with an Ajax call is repeatedly invoked

I am seeking guidance with ajax as I am still new to it. A problem arises when the same ajax call is made multiple times before the previous one completes its execution, resulting in an empty pop-up on the user interface. How can this issue be resolved? Es ...

What are the advantages of using history.push or another method from react-router-dom compared to simply assigning the path to window.location.pathname?

When I need to navigate within my code, I find it more convenient to simply assign the desired path to window.location.pathname. Can this approach have any drawbacks? ...

What is the best way to update my React components to switch from a dark theme to a light theme?

Currently, I am attempting to switch between a light and dark theme in React by utilizing a Switch component from material-ui. Strangely, the theme only toggles once from dark to light. If you want to take a look at the full code, you can find it on this C ...

Tips on postponing the loading of an iframe within a collapsed div using jQuery until the div/button is clicked

So I'm dealing with a bunch of these collapsible divs on a single page, each containing an iframe. (I used some CSS to make it look like a button when clicked). The issue is that the page is loading very slowly because it's loading all the domai ...

Possibility for using navigator.GetUserMedia in Internet Explorer

How can I access a webcam through JavaScript/jQuery? I have successfully opened the webcam in Chrome and Mozilla, but the navigator.GetUserMedia feature does not work in Internet Explorer. Is there a way to achieve this with JavaScript or jQuery in IE? ...

How can I effectively refresh the provider_token / access token for Discord in NextJS with Supabase Auth?

Currently, I have encountered an issue with my NextJs project using Supabase Auth for authentication. I am currently utilizing the Discord provider and everything works fine initially. However, after a few minutes, the session object gets updated and the p ...

Increased wait time during initial execution

Currently facing an issue with delaying the first run of a function. I've developed a basic slideshow that is causing problems due to this delay in the initial run. My goal is to have the first run wait for 10 seconds and then maintain a 4-second del ...

React component that renders conditionally based on the response of an API request

I am working on a status icon that changes based on the number of errors in an object. What is the most effective method for passing data from ComponentDidMount to the function where I want to analyze it? I am trying to aggregate the status in an object, ...

Error: The variable usersWithSecrets has not been declared and therefore is not defined within the current scope. This issue

Despite my best efforts, I keep encountering the same error repeatedly: ReferenceError: D:\Secrets - Starting Code\views\submit.ejs:8 6| <h1 class="display-3">Secrets</h1> 7| >> 8| <%usersWith ...

The functionality of the AngularJS nested router is not functioning properly

I am encountering some challenges with Angular routing, specifically when using nested routes: The current 'abc' state works flawlessly for the route /admin/team/:teamId .state('admin', { url: '/admin', controller: & ...