nuxt-link: take me to the identical position with the hash in the URL

I'm facing an issue with the <nuxt-link> component in my Nuxt application:

  • The first time I click on the link, everything works perfectly and the page is changed as expected.
  • However, if I scroll down a bit and try clicking the link again, nothing happens because the URL is already in the browser's address bar.

Is there a way to override this behavior so that when I click on the nuxt-link, it scrolls to the desired section regardless of previous clicks? (Without refreshing the page)

This is how my nuxt-link is set up:

<nuxt-link :to="{ path: localePath('/'), hash: '#homepage' }"
>
  <span>Homepage</span>
</nuxt-link>

Answer №1

I think it's important to have the ability to add a click handler to your nuxt-link component.

<nuxt-link
  :to="{ path: localePath('/'), hash: '#homepage' }"
  @click.native="scroll"
>
  Homepage
</nuxt-link>

(not sure about the @click.native, if that doesn't work, try using @click)

And then within your methods:

methods: {
    scroll() {
      // implement your scroll function here, which may involve reading document.documentElement.scrollTop or similar
    // if needed, check this.$route to see if the hash is already present before scrolling...
    },
}

Hopefully this helps you get started! Cheers

Answer №2

Managed to get everything working smoothly by implementing this function tied to a click.native event following the guidance of @Merc.

handleScrollToAnchor(anchorId: string): void {
    if (this.$route.hash) {
      const anchor = document.querySelector(`#${anchorId}`)

      // Verify if the anchor has been located
      if (anchor) {
        window.scrollTo({
          // Scroll in a way that positions the anchor at the top of the view
          top: anchor.getBoundingClientRect().top + window.pageYOffset
        })
      }
    }
  }

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

Order Up: Vue Draggable Next feature keeps your lists in line

I need to maintain the order of two lists in local storage so that their positions are saved and retrieved between sessions. In my Vue 3 TS project, I am utilizing this library. Check out the code snippet below: <template> <div> <h3> ...

The art of finding information algorithm

Having a JSON file containing about 10,000 records, each record includes a timestamp in the format '2011-04-29'. Currently, I also have a client-side array (referred to as our calendar) with arrays such as - ['2011-04-26', '2011- ...

Add a CSS class to the text that is selected within a Content Editable div

Hey there, I'm having an issue where the class is being applied to the button when pressed instead of the selected text. Here's my current code: The button needs to be a div, but it might be causing the problem. I just want the highlighted text ...

Stopping CSS animations at a specific point along the path without using timing functions can be achieved by implementing a targeted

Is there a way to pause an animation at the 50% mark for 2 seconds and then resume? P.S. The setInterval method is not recommended! function pauseAnimation() { document.getElementById("0").style.animationPlayState = "paused"; }; var pauseInterval = set ...

The watcher fails to function properly when attempting to pass data from a for loop in the parent component

<div v-for= "(item , index) in chartData" class="col" :key="index"> <ColumnChart :chartdata="item.tactical" :simpletype="true" /> </div> One of the properties I have is called chartData, initially set as an empty array. Upo ...

Encountering difficulty locating a module despite following the correct path according to the official NEXT.js documentation

Recently, I delved into the world of next.js and found myself engrossed in chapter 4 of the official documentation titled "Creating Layouts and Pages." In this chapter, I was prompted to create a file named layout.tsx and insert the following code: import ...

What is the best way to incorporate a for loop in order to create animations with anime.js?

I am currently working on implementing a for loop to create a page loader using JQuery along with the animation framework anime.js var testimonialElements = $(".loader-animation"); for(var i=0; i < Elements.length; i++){ var element = ...

Generating a dynamic sitemap with Next.js

I have been working on a project where I need to create a sitemap, and I am currently using next-sitemap for generation. However, I've encountered an issue with this method, as well as other solutions I've come across, because the sitemap is only ...

The element is not positioned correctly due to the absolute positioning

This is my first attempt at creating a jQuery plugin and I have almost got it working correctly. You can view the example here. I've been struggling for days to position an element as desired. The goal is to display some text with an optional downwar ...

Avoiding the need to wait for completion of the jQuery $.get function

Currently, I am executing a basic jQuery GET request as shown below and it is functioning correctly. $.get("http://test.example.com/do-something", function (data) { console.log("test work done"); }); The GET request is initiated without affecting the ...

Having trouble retrieving AJAX response data using jQuery

I have been searching and attempting for hours without success. On my current page, I am displaying basic data from a database using PHP in an HTML table. However, I now want to incorporate AJAX functionality to refresh the data without reloading the page ...

JavaScript: set values to elements in an array

Below is the code snippet I am working with: function gotData(data){ result = data.val() const urls_kws = Object.keys(result) .filter(key => result[key].last_res > 10) var keywords = urls_kws; c ...

Unlock the power of two-way data binding in Vuex using the mapGetter helper

Understanding how Vuex utilizes two-way data binding involves using set() and get() methods on the computed property of the component. This means returning the store state or relevant getter in the get() method, then committing a mutation in the set method ...

Issues with the HTML required attribute not functioning properly are encountered within the form when it is

I am encountering an issue with my modal form. When I click the button that has onclick="regpatient()", the required field validation works, but in the console, it shows that the data was submitted via POST due to my onclick function. How can I resolve thi ...

Why is the last move of the previous player not displayed in this game of tic tac toe?

Why does the last move of the previous player not show up in this tic-tac-toe game? When it's the final turn, the square remains empty with neither an "O" nor an "X". What could be causing this issue? Here is the code snippet: The HTML code: <div ...

The input value remains a string even after it has been converted to a float

I can't figure out where I'm going wrong. I'm attempting a simple task: getting user input, converting it to a float, and performing a calculation with that value. However, all I keep getting is NaN. Here's the input (I normally replac ...

Identifying the Operating System of Your Device: iOS, Android or Desktop

I am in need of displaying different app download links based on the user's operating system. This includes IOS, Android, or both if the user is accessing the page on a Desktop device. I am currently utilizing React and Next.js for this project. Unfor ...

Firebase disconnect update functionality

I am currently working on a node in firebase that keeps track of all the players in my game. This list is updated whenever new players join. When I, as the current user, disconnect from the game, I want to be able to remove myself from this list. Since th ...

Is it possible to create a DOM element with a click handler all in one step?

I am looking to dynamically create an element, like this: var productItemTop = $( "<span>" + "<a class='spamItemsX' href='#' " + "onclick=" + eval(launchGenericProductSearch(topProducts)) ...

Create a d.ts file for Vue components that are written using Typescript

As a newcomer to Vue, I am eager to dive into creating components and publishing packages to NPM. My plan is to develop Vue (typescript) + Vuetify reusable components that can be easily installed from NPM into any of my projects. While I have successfully ...