Navigate to Element ID with Nuxt.js on click

Currently, I am in the process of developing a Nuxt application and facing a challenge. I want the page to automatically scroll down to a specific element after clicking on a button. Interestingly, the button and the desired element are located within different components but on the same page.

Upon research, I discovered that this is a known issue in Nuxt.js and requires creating a dedicated file for resolution.

To tackle this problem, I created a folder named 'app' and within it, a file called router.scrollBehavior.js with the following code snippet:

export default async function (to, from, savedPosition) { 
    if (savedPosition) {
      return savedPosition
    }
  
    const findEl = (hash, x) => {
      return document.querySelector(hash) ||
        new Promise((resolve, reject) => {
          if (x > 50) {
            return resolve()
          }
          setTimeout(() => { resolve(findEl(hash, ++x || 1)) }, 100)
        })
    }
  
    if (to.hash) {
      const el = await findEl(to.hash)
      if ('scrollBehavior' in document.documentElement.style) {
        return window.scrollTo({ top: el.offsetTop, behavior: 'smooth' })
      } else {
        return window.scrollTo(0, el.offsetTop)
      }
    }
  
    return { x: 0, y: 0 }
  }

The button component, housed in the hero file, contains a click function named goto(). Here's a snippet of the code:

<template>
  <section class="hero-section">
      <div class="left">
          <header id="hero-text" class="hero-header">
            <h1 @click="goto()">Web Development <br> Web Design</h1>
            <p>Hi, ich bin Alex. Ich designe und programmiere moderne, kreative und schnelle Webseiten. Umgesetzt mit den neusten Technologien.</p>
          </header>

        <UiButtonApp
          id="hero-btn"
          text="Schau dir meine Arbeit an!"
        />
      </div>
      <div class="right">
          <img id="hero-img" src="~/assets/img/hero-img.jpg" alt="hero-img">
          <div id="hero-object"></div>
          <img class="dots" id="hero-dots" src="~/assets/img/dots.png" alt="logo">
      </div>
  </section>
</template>

<script>
import { gsap } from "gsap";

export default {
    data(){
        return{

        }
    },
    methods: {
        goto() {
         //Code implementation goes here
            
        }
    }

    }

Now, the lingering question is how to call this function and ensure its functionality? Any insights or advice would be greatly appreciated.

Answer №1

When utilizing router.scrollBehavior.js, define a router action and direct it to a specific hash:

methods: {
    goTo() {
        this.$router.replace({ name: this.$route.name, hash: '#example' });          
    }
}

Remember to assign an id to the component you are navigating to.

<div id="example">
</div>

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

Ways to transfer information from the Component to the parent in AngularJS 1.x

I am facing an issue with my component that consists of two tabs containing input fields. I need to retrieve the values from these input fields when the SAVE button is clicked and save them to the server. The problem lies in the fact that the SAVE function ...

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 ...

Shifting HTML table in Javascript by toggling checkboxes

When I click the checkbox, the table elements are not displaying inline. I am simply hiding the class "box". Do I need to write a special format? By default, the elements are displayed inline but when I check the checkbox, they shift. The column 'Stat ...

Creating a dropdown menu with data loaded dynamically using ajax and json, all without relying on jquery

I am looking to populate a few select menus using JSON data retrieved from my PHP script. Each select menu should display different values based on the selections made in the other menus. While I understand how to clear and fill a select menu using JavaScr ...

What is the best way to access data from this $scope in AngularJS?

Upon printing selecteditems to the console, this is the output: [{"model":"Lumia","brand":"Nokia","subModel":["Lumia 735 TS","Lumia 510"],"city":"Bangalore"}] I have stored it in $scope.details as follows: var selecteditems = $location.search().items ...

Exploring the significance of a super in Object-Oriented Programming within JavaScript

During my studies of OOP in JS, I encountered the super() method which serves to call the constructor of the parent class. It made me ponder - why is it necessary to invoke the parent class constructor? What significance does it hold for us? ...

What is the best way to combine an array of objects into a single object in typescript?

Looking for some help with converting an array of objects into a single object using TypeScript. Here's the structure of the array: myArray = [ {itemOneKey: 'itemOneValue', itemTwoKey: 'itemTwoValue'}, {itemThreeKey: ' ...

Applying conditional statements to an array's parent elements during iterations in JavaScript

Here is my complete script for relevance. I am currently looping through an array from a JSON object and populating content into an HTML div based on the content's ID. The process works well, but I am facing an issue with the logic related to the par ...

Preserve information on page reload in AngularJS

I am currently working on an AngularJS application with Spring REST as the backend. My experience with AngularJS is quite new. Within my UI page, I have a table displaying a list of objects with an edit button for each record. Clicking the edit button ope ...

What is preventing the JQuery dialog from opening?

When I try to trigger a dialog box by pressing the enter key, it is not working as expected. Instead of opening the dialog, it just hides the text. Can someone help me understand what might be causing this issue? <!doctype html> <html lang="en" ...

Creating a Form Input Field Based on a Selection List

I'm in the process of developing a small app to boost my productivity at work. Currently, I have some html/js code that includes a ul with a search filter. When I select an option, it opens a new tab with relevant text. Ideally, I want the outcome to ...

Troubleshooting: Issue with Firestore & Vue Integration - Retaining Data from Function Wrapper

Within my utility file labeled as "FbUtils.js", I have the following code snippet: getUserById(someUserId) { firebase .firestore() .collection("users") .doc(someUserId) .get() .then((snapshot) => { const res = { userId: someUserId, data: s ...

Close the menu when clicking anywhere on the page body

I have successfully implemented a dropdown menu that opens when the navigation button is clicked. However, I am struggling to find a way to close the dropdown menu when the mouse clicks on any part of the page's body. If you have a solution for this ...

Issue with Jquery Drag and Drop functionality, navigate to a different page

I am trying to incorporate a page with js from quotemedia.com using Jquery. When I insert the js into the sortable, and then drag and drop the element containing the js, it suddenly switches to full page display. This issue occurs in Firefox, but IE works ...

Using JavaScript, append a hidden input field in Yii2 and retrieve it from the controller

Seeking assistance as a newcomer to yii2. I'm looking for help in resolving an issue that has arisen. I'm attempting to add a hidden input field to my form using JavaScript (not linked to a model). Subsequently, when I submit the form, I want to ...

Error: Jest encounters an unexpected token 'export' when using Material UI

While working on my React project and trying to import { Button } from @material-ui/core using Jest, I encountered a strange issue. The error message suggested adding @material-ui to the transformIgnorePatterns, but that didn't resolve the problem. T ...

How to manually add the $store parameter to a dynamically created Vue component that is missing it during creation

I'm a newcomer to the world of Vue/Nuxt and I've encountered an issue while attempting to dynamically generate a Vue component on button click using the following code: async addComponent(componentsItem) { var ComponentClass = Vue.component(&a ...

tips for selecting various API requests based on the selected drop down menu choice

Hey there! I'm looking to enhance my login page by adding a feature that allows users to select from a dropdown menu with different options. Each option will be linked to a specific API, and based on the API response, the user's ability to log in ...

Newly included JavaScript file displays on view page, but triggers a 404 error when attempting to open

Once I implemented the following code in the child theme's function.php file: add_action('wp_enqueue_scripts', 'js_files'); function js_files() { wp_register_script('ajax_call_mkto', get_template_directory_uri() . ' ...

Having trouble with npm debounce in ReactJS?

When using the npm debounce package in ReactJS, I encountered an error with the code below: Javascript - Uncaught TypeError: Object(...) is not a function The error occurs when passing the function into the debounce() method. import React, { Component ...