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

Upon the creation of a new Post and attempting to make edits, the field is found to be blank

<template> <div class="card m-3"> <div class="card-body"> <Form method="post" @submit="submitData" :validation-schema="schema" ref="myForm" v-slot="{ errors, ...

Transform this color matching game into an image matching game using JavaScript and jQuery

I have a color matching game that I would like to enhance by matching background-images instead of just background-colors. However, I am facing difficulties in making this change. For instance, instead of matching the color red with the text "red," I wan ...

Switch the CSS class when clicking on a responsive table within a table

I am looking to update the background color of a row within a table when a tr is clicked. Below is the code for the table: <div class="table-responsive"> <table class="table table-hover"> <thead> ...

Using the setTimeout function within the created lifecycle hook in Vue.js

methods: { displayMessage() { console.log("Hello World"); } }, created() { setTimeout(this.displayMessage(), 5000) } I have my code snippet here. I am trying to use setTimeout in the created hook, but the browser is not recognizing ...

A messaging application powered by socket.io and the Express JS framework

I am currently learning Node.js and I am encountering an issue with using socket.id to identify logged in users on the client side using their email id and password. The verification process happens on the server side, and if successful, the user's so ...

Executing a function following the removal of an element

I am trying to remove an element after exiting a jQuery dialog. I have used the .remove() function, but the element is not accessible after executing .remove(). How can I "destroy" an object in JavaScript and allow it to be called again without refreshing ...

Extracting textual information from Wikipedia through iframes?

Currently, I am working on a website project utilizing Squarespace. This site will feature multiple pages dedicated to individuals who have reached a level of notability worthy of having their own Wikipedia page. With over 150 pages planned, manually writi ...

Show User-Specific Information Using DataTable

After conducting extensive research, I have been unable to find a suitable example to reference. My goal is to customize my DataTable so that it only displays data relevant to the currently logged-in user (admin accounts will have access to all data). I am ...

Adding several entries into mysql with the assistance of php

I've been attempting to input multiple records into my database table, but every time I try, all I see are zeros(0) inserted into the fields. Here's what I attempted: I used a foreach loop for insertion, but unfortunately it doesn't seem to ...

What is the best way to pass a variable and its corresponding state-updating function as a prop in a React component?

Considering I have a variable defined as follows: const [APIKey, setAPIKey] = useState([]) Is it possible to group these together into a single variable and then pass it as a prop? const passAPI = {APIKey, setAPIKey} Here is my approach to passing it alo ...

Tips for inserting information from a JSON file into a mailto hyperlink

As a newcomer to JavaScript, I am eager to tackle the challenge presented below: Situation: In possession of a JSON file containing personal details such as name, email address, bio, etc., my task is to design a basic web page showcasing this data for ea ...

Turn off Appbar padding at the top and bottom

I am looking to create a customized box within the Appbar that spans the full height, as illustrated in the image below: https://i.stack.imgur.com/CFMo0.jpg However, the default Appbar provides padding from all sides to its internal elements, leading to ...

How to Delete Elements from an ngList Array in Angular

I encountered an issue while utilizing ngList in a text box to exchange data with my server. The problem arises when I attempt to delete items from the generated array directly, as it does not reflect the changes in the input field. The main concern is th ...

Having issues with accessing data from Informix database in PHP due to an undefined index?

I am encountering the following error multiple times per row: Notice: Undefined index: enviopre in /opt/lampp/htdocs/pruebax/pruebaxone.php on line 34 Notice: Undefined index: enviofra in /opt/lampp/htdocs/pruebax/pruebaxone.php on line 35 Notice: Undef ...

Retrieve the user_id without triggering any route

Is there a way to access the logged in user data without needing to make a request to any route or endpoint? //for example, how can I retrieve the id of the logged in user here? router.get('/',function(req,res,next){ //typically we would acce ...

Verifying the authenticity of a Stripe discount code

My goal is to allow users to apply a coupon code on my website, triggering a check in the Stripe dashboard. Currently, I have implemented the following code snippet, but I am facing an issue with transferring the validCoupon data from the client side to th ...

The animation in Material UI does not smoothly transition with the webkit scrollbar

I've been experimenting with CSS animations in Material UI's sx property to achieve a webkit scrollbar that eases in and out. However, instead of the desired effect, the scrollbar appears and disappears instantly. Whether I define the keyframes ...

Exploring the power of Google Maps Radius in conjunction with AngularJS

I am currently developing an AngularJS app that utilizes a user's location from their mobile device to create a dynamic radius that expands over time. You can view the progress of the app so far by visiting this link: . The app is functional, but I a ...

Click on a designated button to choose a specific file on an HTML page

I need to be able to select a specific file by clicking on another button. A helpful solution that utilizes JavaScript to trigger the selection of a hidden file can be found in this answer. You can view the implementation here. In my scenario, I alre ...

Activate the Air-mode feature in Summernote in addition to the standard toolbar

Is it possible to have both the default toolbar and air-mode toolbar enabled in the Summernote editor? For instance, I would like the user to utilize the default toolbar for general text editing, but have the air-mode toolbar appear when they select a spe ...