How to implement scrollIntoView in Vue 3 with script setup

Having some trouble with scrolling to a specific element when clicked. I keep getting this error message.

Uncaught TypeError: element.scrollIntoView is not a function

Here is my script

<script setup>
import { ref } from 'vue'

function goTo(refName){
    let element = ref(refName);
   element.scrollIntoView({behavior: "smooth"})
}

</script>

This is the click function

<DayWithText v-for="day in daysOfWeek" :name="day.shortHand" :day="day.day" :date="day.date"  @click.prevent="goTo('test')"/>

And here is the element causing issues

<p ref="test">test</p>

Any ideas on what might be going wrong?

Answer №1

ref('test') doesn't just return

<p ref="test">test</p>
, it actually creates a new ref with the initial value of 'test' (a string).

If you want to access that paragraph, you need to declare it as:

const test = ref(null)

inside the <script setup> block (before mount is called).

After the component has been mounted, you can use the following code:

test.value?.scrollIntoView({behavior: "smooth"})

This will work as expected.

Check out the demo below:

const { createApp, ref } = Vue;
createApp({
  setup() {
    const test = ref(null);
    const goToTest = () => {
      test.value?.scrollIntoView({behavior: "smooth", block: "center"})
    }
    return {
      test,
      goToTest
    }
  }
}).mount('#app')
#app p {
  margin: 200vh 0;
}
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4335362603706d71">[email protected]</a>/dist/vue.global.prod.js"></script>
<div id="app">
  <button @click="goToTest">Go to test</button>
  <p ref="test">test</p>
</div>


Behind the scenes, on mount, when the <template> parser encounters a ref, it searches the setup scope for the declared variable with that name. If found and if it's a ref, the current DOM element is placed in that ref's value.

Answer №2

For my scenario

const reference = ref(null);

const scrollPage = () => {
    reference.value.$el.scrollIntoView({behavior: "smooth"});
}

html

<div @click="scrollPage()">scroll to</div>
<p id="reference">Scrolled position</p>

was successful for me

Answer №3

This is my solution to the problem.

<script lang="ts" setup>
const scrollPage = ()=> {
    document.getElementById("upButton")?.scrollIntoView({behavior: "smooth"});
}
</script>
<template>
<div>
   <div id="upButton" class="content">
      Some random text...
   </div>
</div>
</template>

Answer №4

When it comes to typescript, the code would look like this:

    const element = ref<null | HTMLDivElement>(null);

    element.value?.scrollIntoView({behavior: "smooth"})

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

Clicking on the anchor at the bottom of the page will smoothly navigate you to the top of the page

I added an anchor at the bottom of the page. I wrapped a group of buttons with the link so that when clicked, they trigger the assigned JavaScript and scroll to the bottom of the page. However, the buttons currently execute the JavaScript but then take you ...

Remove a div element with Javascript when a button is clicked

I am working on a project where I need to dynamically add and remove divs from a webpage. These divs contain inner divs, and while the functionality to add new divs is working fine for me, I'm facing some issues with removing them. The code snippet b ...

Prevent side menu from automatically hiding when clicking on the heading

My menu is set up with headings and subheadings. When I click on the headings, it expands to display the corresponding subheadings, but it automatically collapses when clicking on the headings. I want it to stay expanded when clicking on the headings. He ...

What is the process for saving an SVG element from an HTML page as a downloadable text file?

I've been practicing creating SVG elements from scratch on an HTML page using Javascript. The texts within the SVG element are styled with typefaces fetched from the server through a "@font-face" declaration in the CSS file. It's been quite succe ...

Reading an XML file to locate items nested within the same bracket

Within my JavaScript function, I am utilizing the following code to extract data from an XML file: var title = $(this).children('Title').text(); This snippet of code successfully retrieves the content under the <Title> tags: <Title> ...

Using Angular and Typescript to implement a switch case based on specific values

I am attempting to create a switch statement with two values. switch ({'a': val_a,'b': val_b}){ case ({'x','y'}): "some code here" break; } However, this approach is not functioning as expected. ...

Is there a way for me to showcase a collection of pictures in an array format

I am facing an issue on my react page where the data is successfully fetched from an API, but I am having trouble fetching the array of images. Below is the code snippet that I have written: import React, {Component} from 'react'; export defaul ...

Vuetify vintage vibes

I recently started working with Vue/Vuetify and decided to use the vuetify v-text-field tag with the outline prop. Why is the label displaying like it is in the image? Additionally, the font doesn't appear to be the Vuetify default one. This is my ...

Using a package with `webfontloader` in NextJs for Server-Side Rendering: A guide

Currently, I am working on creating an application with nextJS and incorporating a package that utilizes Webfontloader internally. After installing the library, my application encountered an error preventing it from running successfully. It seems like th ...

Do the items appear on screen only once you start typing in AngularJS?

Most things are working well except for a couple of issues Code var app = angular.module("MyApp", []); app.filter('offset', function() { return function(input, start) { start = parseInt(start, 10); return input.slice(start); }; } ...

Guide to setting up a custom js file in Laravel admin template

Currently working with Laravel 5.8 and utilizing the laravel-admin Template for administrative purposes. There are times when I require custom JavaScript and CSS files specifically for certain admin controllers. How can I include these JS and CSS in lara ...

Interacting with Apexcharts: Exploring a Tiny Column with Hover

While using apexcharts, I encountered an issue with small columns. It can be quite challenging to render the tooltip properly because you have to hover very precisely over the column. Query: Is there a way to expand the hover area to make it easier to int ...

Adjust the size of icon passed as props in React

Below is the component I am working on: import ListItemButton from '@mui/material/ListItemButton'; import ListItemIcon from '@mui/material/ListItemIcon'; import Tooltip from '@mui/material/Tooltip'; const MenuItem = ({data, o ...

Spinning a CSS object around an axis

Trying to add a unique touch to my image rotation with CSS. While familiar with rotating around x, y, and z axis, I want to achieve a diagonal rotation this time. Wondering if there's a way to tweak the y axis for a more slanted effect on my image? ...

I keep encountering a parser error when making an AJAX call to retrieve JSON data. It seems to be caused by

here is a snippet of code I am working on $.ajax({ type: 'GET', url: "<%=request.getContextPath()%>/manageUsers.do", cache: false, data:{ "resultType": "json", "submit": $.i18n.prop('esadmin.manage.users ...

Using Angular to automatically update the user interface by reflecting changes made in the child component back to the parent component

Within Angular 5, I am utilizing an *IF-else statement to determine if the authorization value is true. If it is true, then template 2 should be rendered; if false, then template 1 should be rendered. Below is the code snippet: <div *ngIf="authorized; ...

Guide to modifying the root directory when deploying a Typescript cloud function from a monorepo using cloud build

Within my monorepo, I have a folder containing Typescript cloud functions that I want to deploy using GCP cloud build. Unfortunately, it appears that cloud build is unable to locate the package.json file within this specific folder. It seems to be expectin ...

The search box output will be the same as the JSON result

I have a server in Node.js that is able to read and process a JSON file containing various data, including unique user IDs. I have incorporated a search box into my HTML page, and I am seeking assistance with creating a jQuery method (which will require AJ ...

What is the reason behind the NextJS logo not being displayed when accessing the page via its URL?

My logo isn't displaying on the /page URL View Screenshot Check out my components/LayoutWrapper.js import Image from 'next/image' import icon from '../assets/images/Icon.svg' <div className="flex items-ce ...

Leveraging callback functions for dynamically updating a JSON structure

Recently, I've been working on a db_functions.js file that includes several functions designed to interact with a database. Here's an excerpt from the script: function getUsers(client, fn){ //var directors = {}; client.keys('*' ...