Guide to seamlessly navigating to an element using a hash in NuxtJS

My aim is to create a smooth scrolling anchor link menu using Nuxt.js, where the user can click on a link and be directed to the corresponding page section. However, I'm facing a dilemma as there are multiple approaches to achieve this functionality, and I'm unsure which one is the most suitable.

Option 1:

In my first attempt, I implemented a menu that calculates the offsetTop of each section div to determine the scroll distance when a user clicks on a menu link. The issue with this method is that certain values of the divs, such as offsetHeight and offsetTop, tend to change when the project is deployed to the server. Consequently, the links end up scrolling to incorrect positions and do not function correctly.

I experimented with swapping the order of the 'Value' and 'Problem' sections, which temporarily resolved the problem. However, the correct sequence of sections needed to be maintained.

In this approach, I utilize the created() lifecycle hook to retrieve these values and store them in Vuex state. These values are then accessed in another component where the menu functionality resides:

.................................... (The rest of the original content remains unchanged) ..........................

Now, I find myself torn between these two options, unsure of where to invest my time and effort for the best outcome.

Answer №1

Your operations here are quite complex and may vary across different browsers. I suggest sticking with a Vue approach instead of vanilla JS for better compatibility.

I was able to implement a local scroll functionality following my previous answer and by adding the code in /pages/index.vue

<template>
  <div>
    <button
      v-scroll-to="{ el: '#scroll-here', duration: 300 }"
      @click="$router.push({ name: 'index', hash: '#scroll-here' })"
    >
      Let's scroll !!
    </button>
    <nuxt-link to="/about">go to about page</nuxt-link>

    <p class="big-block">
      (Content)
    </p>

    <p id="scroll-here">scroll smooth to here please</p>

    <p class="big-block">
      (More content)
    </p>
  </div>
</template>

<script>
export default {
  name: 'Index',
}
</script>

<style>
.big-block {
  min-height: 100vh;
}
</style>

We utilize vue-scrollto package to target our ID, all available options can be found here.

If you want a global behavior, check out my answer here with the code in /app/router.scrollBehavior.js

import Vue from 'vue'
import VueScrollTo from 'vue-scrollto'
Vue.use(VueScrollTo)

export default function (to, from, savedPosition) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (to.hash === '#scroll-here') {
        VueScrollTo.scrollTo('#scroll-here', 300, { easing: 'linear' })
      }
    }, 10)
  })
}

You can choose between a local solution per button or a more widespread global one based on your requirements.


You can view a demo of both local and global scrolling solutions here (reduce browser viewport size for best experience).
The related repository is hosted on GitHub here.

Answer №2

Defining what is considered "correct" in development can be a challenging task. In my opinion, the concept of "correct" revolves around functionality...

When deciding on which path to take, it's important to consider whether Vue.js tools are advanced enough for your specific needs. If they are primarily designed for simplifying complex processes, this might be causing issues with option 2. In such cases, it may be more effective to utilize CSS and vanilla JS to craft a refined solution rather than trying to force fit framework tools. Based on your description, it appears that solution 1, utilizing mostly vanilla JS, is performing better than solution 2. Remember, JavaScript is a fundamental skill possessed by all web developers. Therefore, if a problem can be elegantly solved using vanilla JS instead of within a particular framework like Vue, it may be wise to opt for the former.

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 best way to implement validation in a textarea to restrict the word count to a minimum of 250 and a maximum

I want to implement jQuery validation for a textarea field, with a requirement of 250 minimum words and 1000 maximum words. Additionally, I need to display the word count in a span tag next to the text area. How can I ensure that this validation works even ...

Is there a way to extract the properties of a CSS class from a stylesheet and convert them into a hash using JavaScript or jQuery?

I am exploring a way to extract key value pairs from a CSS stylesheet related to a specific class or id into a JavaScript object for data accessibility. It is important to mention that I do not intend to apply this class directly to any DOM elements. In ...

Display modal within a React list

I need to display a list of items with an edit button for each item, which should trigger a modal showing the details of that specific item. Initially, I had a single modal component in the parent element and passing the visible values to the parent state ...

Having trouble with Node JS res.redirect() not functioning as desired?

I'm attempting to use res.redirect() to redirect to an external URL, but the host name isn't being replaced. For example: My current URL: https://example.com Desired redirect URL: When I use res.redirect("https://example-2.com/pqr?par=123 ...

I'm seeking assistance with a frontend script problem. I'm curious if there are alternative approaches to coding this script that may be more effective. Can anyone offer guidance on this?

As a frontend developer specializing in script injection, I have been utilizing Adobe Target to inject scripts. However, this method presents several challenges: 1. It is difficult to debug code errors as my HTML and CSS are wrapped inside ' ' a ...

Guide on integrating HTML from a response into the render function in React JS

I've been doing some research but I'm struggling to find a good solution for this issue. I have a response that looks like this: "name": "another test", "description": "para hacer el aseo", &quo ...

Looking for a way to choose a button with a specific class name and a distinct "name" attribute using jquery?

I am currently working on developing a comment system. As part of this system, I want to include a toggle replies button when a user posts a reply to a comment. However, I only want this button to be displayed if there are no existing replies to the commen ...

Building a personalized version with core-js

I am currently in the process of developing a custom build using core-js. Following the instructions provided, I initiated the following commands: npm i core-js && cd node_modules/core-js && npm i The process seemed to go smoothly. Then, ...

The Ajax function effortlessly receives the returned value and smoothly transitions to the error handling stage

When trying to retrieve data from an ajax request, my function needs to receive the returned data as an array of strings. During debugging, I am able to see the response, but at the same time, the error function is triggered. This is how my code looks: ...

Guide on excluding a specific element using an Xpath expression

I am seeking a solution to craft an XPath expression that can target all <p> elements except for p[6] and p[7]. Currently, I have formulated this expression: //div[@class="Job-Description app-responsive-jd"]/p[1], which is functioning corre ...

Sending data between PHP and JavaScript using Ajax communication

I am currently working on a PHP page that involves variables and radio buttons. When a user clicks on a radio button, it triggers a JavaScript function to calculate the price of the selected item by passing some variables. Here's how I have implemente ...

Creating a Click Counter with jQuery 2.0.1/2.0.2: A Step-by-Step Guide

Currently in the process of creating a fundraising webpage for charity, I have chosen to display an animated rabbit making its way Around The World. My progress so far includes a non-looping gif that plays on click, with a limitation on how often it can b ...

Access various data from the local storage and display them inside a div container

I am trying to display the keys and their values for all the data stored in the local storage. Here is the HTML and JavaScript code I have written: // Setting some values in the local storage localStorage.setItem("lastname", "Smith"); localStorage. ...

Incorporating Font Awesome into a Vue.js project

I followed the instructions in the Vue project documentation to install font-awesome, but encountered an error: Initially, I used the following commands for installation: $ npm i --save @fortawesome/fontawesome-svg-core $ npm i --save @fortawesome/free-so ...

Implementing the onClick function for the correct functionality in a ReactJS map component

I have designed a mockup and now I am trying to bring it to life by creating a real component. View my component mockup here Starting with something simple, I created 3 buttons and an array. However, when I click on any button, all features are displayed ...

How come React.js is not displaying images from local URLs?

In my React application, there is a form where users can submit an image file. To store the path of the submitted image locally for browser access, I utilized URL.createObjectURL to generate a URL for the file. Here is the code snippet: handleImageChange(e ...

Why is jQuery ajax not functioning in the view file in a node.js environment?

I have recently started working with Express Node.js and I am facing an issue with making an AJAX call or using jQuery from the HBS view. Below are my controller methods: router.get('/', function(req, res) { console.log("home get request"); ...

Having trouble uploading files with jQuery File Upload functionality

Issue: I need to set a session variable and redirect the user to a different PHP page after uploading a .txt file using jQuery File Upload. HTML code (upload.php): <!-- The fileinput-button span is used to style the file input field as button --> ...

Maximizing Performance: Enhancing Nested For Loops in Angular with Typescript

Is there a way to optimize the iteration and comparisons in my nested loop? I'm looking to improve my logic by utilizing map, reduce, and filter to reduce the number of lines of code and loops. How can I achieve this? fill() { this.rolesPermiAdd = ...

Improving sharing functionality across multiple VuGen scripts executed through Performance Center

I have multiple VuGen scripts that utilize the Web/HTTP protocol with javascript. Currently, I am using VuGen 12.53 (patch 4) and have a common login.js action in all of my scripts. Whenever I need to make changes to the login action, I have to update ever ...