Watching for changes to an element's visibility within the viewport and automatically scrolling it

I'm having trouble making the input scroll to .here when its value matches "1". Even though I tried using a button with a handle-click function and it worked.

Please lend me a hand with this issue.

<template>
  <button @click="scrollToView">Click to Here</button>
  <input type="text" v-model="searchAddress" />
  <span v-if="matchAddress">OK</span>
  <span class="here" ref="el">Here</span>
</template>

<script setup>
import { ref, computed, watch, nextTick } from "vue";
const searchAddress = ref(null);
const el = ref(null);
const matchAddress = computed(() => {
  return searchAddress.value == 1;
});
function scrollToView() {
  el.value.scrollIntoView({ behavior: "smooth", block: "center" });
  el.value.focus({ preventScroll: true });
}
watch(matchAddress, async (val) => {
  console.log(val);
  if (val) {
    await nextTick();
    scrollToView();
  }
});
</script>

DEMO

Answer №1

There appears to be a compatibility issue with Chrome in this situation. It seems that the nextTick() function is being triggered too early. This could be due to an event generated by the keyup function preventing Chrome from scrolling the <input> element out of view. As a result, the button may work properly but not the text input field.

A possible workaround is to use a setTimeout() method:

watch(matchAddress, async (val) => {
  if (val) {
    setTimeout(() => scrollToView());
  }
});

Answer №2

Here's a simple solution you could experiment with. While the example below uses vanilla JS, in Vue.js all you have to do is switch onkeyup(event) to @keyup($event). Additionally, the window.scrollTo may need to be changed to outerComponent.scrollTo. Just input "1" into the field.

function verifyInput(event) {
  const userInput = event.currentTarget.value
  const divLocation = document.querySelector('.location')
  if (userInput === '1') {
    
    // In Vue.js, consider replacing "window" with your outer component reference.
    window.scrollTo({ 
      top: divLocation.offsetTop,
      behavior: 'smooth'
    })
  }
}
.location {
  width: 50px;
  height: 50px;
  margin-top: 800px;
  background-color: blue;
}
<input type="text" onkeyup="verifyInput(event)">
<div class="location">

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

Using getElementsByTagName in E4X code involves querying for specific

Is it possible to retrieve an array of elements in E4X for an unknown tagname, similar to how the DOMs getElementsByTagName function works, within a function? My initial idea was: (function (doc, tag) { return doc..[tag]; }) Can this be achieved? ...

Adjust the variable value if the "for" loop encounters an error

In my situation, I have a spreadsheet that contains a script responsible for checking another linked spreadsheet for a customer's name and then returning the associated code. Everything works smoothly when the customer name is found in the "CustomerCo ...

Is it possible to utilize the output of a function to determine the styling of a div element in Vue?

Hi, I'm trying to use the v-bind:style in my div to apply the textposit function with the textpos prop as a parameter. The function should adjust the style of the div based on the value of the parameter. <div class="container" :style=&qu ...

Error: The parent container element cannot be edited until the child element has been properly closed

I received a Script Error stating that I am unable to modify the parent container element before the child element is closed. In response, I clicked Yes but my web page isn't being displayed. In the code for my Product page, I start with: http://past ...

Vuejs fails to properly transmit data

When I change the image in an image field, the new image data appears correctly before sending it to the back-end. However, after sending the data, the values are empty! Code Commented save_changes() { /* eslint-disable */ if (!this.validateForm) ...

Acquiring the API through the callback function within a React application

I wrote a function that connects to an API and fetches data: import {API_KEY, API_URL} from "./constants"; export const getOperations = async (id, successCallback) => { try { const response = await fetch(`${API_URL}/tasks/${ ...

Guide to invoking a mixin function within middleware

Is there a way to invoke the mixin function within middleware using NUXT.js? This is what I have attempted: export default function(context) { // initialize auth token from local storage or cookies context.initAuth(context.req) if (!context.store. ...

"Bower fetches and installs specific versions of packages from the repository

I'm currently using npm 3.3.6 and bower 1.6.8 on Windows 10. Whenever I attempt to install a package like jquery or framework7, it ends up downloading and installing an archived version of the package. Here's an example: > bower install jquer ...

Extension: What is the best way to leverage data obtained from an ajax request in order to dynamically modify an already existing element within

I've been trying to find a reliable and comprehensive tutorial for JavaScript (JS) and Ajax, but so far my search has been futile. Unlike Python.org for Python or php.net for PHP, I haven't found a satisfactory resource yet. Any recommendations w ...

Returning a value with an `any` type without proper validation.eslint@typescript-eslint/no-unsafe-return

I am currently working on a project using Vue and TypeScript, and I am encountering an issue with returning a function while attempting to validate my form. Below are the errors I am facing: Element implicitly has an 'any' type because expression ...

What is the recommended way of inserting new data into a table in vue.js?

Is it possible to update the table data whenever I want, even after initializing the Vue instances? I've attempted to use the following methods but the data is still not updating: ・$nextTick ・$set <script> var overall = new Vue({ ...

Highcharts 3D Pie Chart with Drilldown Feature

How can I create a 3D Pie Chart with Drilldown effect? I am having trouble understanding how it works. Here is a JsFiddle Demo for a 3D Pie Chart: JsFiddle Demo And here is a JsFiddle Demo for a 2D Pie Chart with Drilldown feature: JsFiddle Demo You can ...

bindings and validation of input values in angularjs

In my scenario, I am dealing with a dynamic regExp and unique masks for each input. For instance, the regExp is defined as [0-9]{9,9} and the corresponding mask is XXX-XX-XX-XX. However, when it comes to Angular's pattern validation, this setup is con ...

A function that can retrieve distinct values for a specific property within an array of objects while maintaining their original order

Here is some information I have: $scope.Reports = [ { Id: 1, Name: 'Report One', Year: 2016, Month: 5 }, { Id: 2, Name: 'Report Core', Year: 2016, Month: 5 }, { Id: 3, Name: 'Report Alpha', Year: 2016, Month: 3 }, { I ...

Utilizing Next.JS and Nodemailer to seamlessly send emails through a contact form

I'm facing an issue with my contact form in next.js. Everything was working fine until I deployed it on Vercel. Although I don't see any errors, I am not receiving emails on my Gmail account after submitting the form. Additionally, I am not getti ...

Unraveling deeply nested array objects in JSON with Java Script/jQuery

I need help working with a JSON file that looks like the following: {[ {"name":"avc"}, {"name":"Anna"}, {"name":"Peter"}, {"Folder":[ {"name":"John"}, {"name":"Anna"}, {"Folder":[ {"name":"gg"}, ...

A guide on accessing objects from an array in Vue.js

Wondering how to choose an object from an array in Vue.js: When the page loads, the selectTitle() function is triggered. I simply want to select a specific object (for example, i=2) from my 'titleList' array. However, at the moment, I am only re ...

Using jQuery to show and hide elements on a webpage

One issue I'm facing is changing the content on a page depending on the clicked link. The problem arises when the displayed content for one link persists even after clicking another link, despite setting it to not display when another link is clicked. ...

My website using Dynamic Ajax technology is currently experiencing heavy traffic due to the number of getScript

I am facing an issue with my dynamic website where all links fetch new sections via ajax requests from other pages and replace the current section. The problem I encounter has two main aspects. When loading a new div from an Ajax get request, some sections ...

What is the best way to upload a file using AJAX request in Sinatra?

I am attempting to upload a file using a jQuery AJAX function with a Ruby-Sinatra function. Here is the code snippet: <form id="ucform" method="post" action="#" enctype="multipart/form-data"> <input type="file" id="cfile" name="cfile" onchange= ...