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.