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

"Exploring the power of Vue.js through dynamic and recursive components

I am struggling with creating a recursive custom component that calls itself. Unfortunately, I keep encountering an error. An unknown custom element: <TestRec> - have you registered the component correctly? For recursive components, ensure to specif ...

Tips for concealing a "PARTICULAR TAB BAR ITEM" on a bottom tab bar in @react-navigation/bottom-tabs

Check out this video displaying my current visible bottom tab items: Home, My Account, Cart, and Menu. Watch here I have additional bottom tab items like SettingsView that I want to render on the screen but keep them hidden from the bottom tab bar itself. ...

Developing components with jQuery

I have a JavaScript program that works perfectly when I use the following line of code: li = $("<li data-role='collapsible' data-iconpos='right' data-inset='false'></li>"); However, if I change the above line ...

Is it considered acceptable to retrieve the action payload in mapDispatchToProps in a React/Redux setup?

In my MediaUpload component, I have a mapDispatchToProps function that handles file uploads. When a file is added, the onChange handler triggers two actions: creating new media entries for the files and updating the form data in the state with the generate ...

Employ a for loop to generate custom shapes within the canvas

EDIT: I will be sharing all of my code including the HTML and JS. Pardon me for the abundance of comments. I am attempting to generate rectangles in a canvas using a for loop (taking user input) and then access them in another function to perform certain ...

Tips for associating an id with PrimeNg menu command

Within my table, I have a list of items that I would like to enhance using PrimeNg Menu for dropdown menu options. The goal is to enable navigation to other pages based on the selected item id. When a user clicks on a menu item, I want to bind the id of th ...

I found myself puzzled by the error message "Module protobufjs not found."

I am currently utilizing the node library known as node-dota2. I have completed all the necessary steps required by node-dota2, as outlined on this site: https://github.com/Arcana/node-dota2#installation-and-setup 1. Installed it using npm 2. Created a fil ...

Is there a way to set the chosen option on a dynamically loaded secondary select using VueJS?

I am working with a city select dropdown: <select v-model="city"> <option value="" selected>SELECT YOUR CITY</option> <option value="city1">City 1</option> <option value="city2">City 2</option> < ...

Guide to organizing files with custom directory layout in NodeJS

Imagine having multiple files spread across various folders. /parentDir/ |__dirA/ |__file1 |__file2 |... |__dirB/ |__file3 |... |... You want to consolidate them into an archive, with the option of using something like ...

Retrieving the name of an object from an array using Javascript

const crypto = require("crypto-js"); const hashFunctions = [crypto.MD5, crypto.SHA1, crypto.SHA256, crypto.SHA224, crypto.SHA512, crypto.SHA384, crypto.SHA3, crypto.RIPEMD160]; console.log(JSON.stringify(hashFunctions[0])); The above code outputs undefin ...

What is the conventional method for sending data by utilizing the output of a previous data submission in Node.js with Express and FaunaDB?

I am in the process of revising a project and have a question about how to post an array of data using the return value of a previous post request as the ID. Here is an overview of the data structure: Checklist A [ChecklistItem 1, ChecklistItem 2, Checkli ...

Error message in Angular js: Unable to load file using XMLHttpRequest

Encountering an error while debugging an Angular JS application in the WebStorm IDE. The error message states: "XMLHttpRequest cannot load file:///C:/Users/../list.html. Cross origin requests are only supported for HTTP." Provided Javascript code : var a ...

Choose a portion of the content within a div element

In my SVG element, I have created a foreignObject with a textarea and a div inside. The textarea is transparent and lies on top of the div. As users type in the textarea, the text gets copied to the div creating a WYSIWYG editor. Everything functions corre ...

How to successfully close a jQuery dialog within a user control

My user control has a list view with a hyperlink (LnkDelete) that triggers a jQuery dialog. Here is the javascript code responsible for this functionality: $('#LnkDelete').live('click', function (e) { var page = $(this).at ...

In Vuex, the getters always come back as true

The isLoggedIn in getters is always true even if there is no token from API. I can still go to every route; I don't know what the error is in the guard route or if I'm storing the token wrong in the state. This statement is not working: if(!store ...

Utilizing API data as props within an Autocomplete component in Reactjs with Material-UI

New to Reactjs, I am currently exploring the implementation of the Autocomplete component from material-ui. My goal is to pass the API link as a prop to the element. However, I'm stuck on how to pass the json label name as a prop to be used in "getOpt ...

Shuffle the setInterval function: How to consistently rewrite with random intervals?

Seeking guidance on how to implement the following task: generate a random number after a random amount of time and then reuse it. function doSomething(){ // ... do something..... } var rand = 300; // initial random time i = setInterval(function(){ ...

Exploring the intricacies of Knockout JS mapping nested models using fromJS function

I am struggling with understanding how to effectively utilize the Knockout JS Mapping Plugin. My scenario involves nested models, and currently I am only using the ko.mapping.fromJS() in the parent model. However, I have noticed that the computed values ar ...

Encountering a problem: The function _ctx.openNote is not recognized as a function when attempting to click on a note for viewing

I started with my notepad app from the ground up, which can be found on this link: Issues with data bind in vue.js and events The problem I encountered was that I couldn't click on the note from NoteList.vue to view the details. There seems to be a d ...

What is the best way to set tab spacing within a textarea using ReactJS and Bootstrap?

One of my goals is to adjust the indentation within the text area by a specific amount when the Tab button is clicked. I am utilizing React JS and Bootstrap. Within the render function, I have set up a bootstrap text area as shown below: <textarea cl ...