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

Guide on implementing text/ng-template script section in jsfiddle

My current challenge involves creating a jsfiddle that utilizes AngularJS to display two calendar controls. While my code functions properly when run locally, I've encountered an issue with including the template code via a script tag on jsfiddle: ht ...

The characteristics that define an object as a writable stream in nodejs

Lately, I've been delving into the world of express and mongoose with nodejs. Interestingly, I have stumbled upon some functionality that seems to work in unexpected ways. In my exploration, I noticed that when I create an aggregation query in mongoos ...

Retrieve elements from an array based on the value of an object

I have a list of items that resembles the following structure: var entries = [ { sys: {id:"1"}, fields: "article1" }, { sys: {id:"2"}, fields: "place1" }, { sys: {id:"3"}, fields: "offer2" }, { sys: {id:"1"}, fields: "article2" }, { sys: {id:"1" ...

Organize the HTML output generated by a PHP array

There must be a simple solution to this, but for some reason, it's escaping me right now. I've created custom HTML/CSS/JS for a slider that fetches its content from an array structured like this: $slides = [ [ 'img' = ...

The cookie appears in the callback URL, but does not get stored in the browser's cookie storage

I'm attempting to store the facebookPicUrl image in a cookie. Even though I can see it in the callback request, it's not showing up in the browser's cookie storage. Just to clarify, the session cookie is working fine. auth.route('/auth ...

A guide to sorting JSON objects in Node.js

let data={ '0': { benchmark: null, hint: '', _id: '54fe44dadf0632654a000fbd', date: '2015-05-10T01:11:54.479Z' }, '1': { benchmark: null, hint: '', _id: ...

Am I on the right track with incorporating responsiveness in my React development practices?

Seeking advice on creating a responsive page with React components. I am currently using window.matchMedia to match media queries and re-rendering every time the window size is set or changes. function reportWindowSize() { let isPhone = window.matchMed ...

Troubleshooting Vue computed property access issues

Currently, I am in the early stages of learning Vue and have moved on to exploring validation. While looking at some older examples that utilize Vee-Validate, it seems that there has been recent changes to the library. How can I update this code to work w ...

Is it possible to share a MySQL connection for cross-module usage in Node/Express by utilizing promise-mysql?

Currently, I am trying to import and utilize a database module within one of my controllers. Despite successfully establishing the initial connection, I am encountering an error when accessing any of my routes through the browser: "Cannot read property ...

Create an instance using the window object in JavaScript

Having an issue when trying to instantiate a class using the window object. I have a namespace called UTIL and within it, there is a class defined as follows: var UTIL = { Classes : {}}; UTIL.Classes.ObservationVal = function(state, id, type, context, pe ...

Instructions on incorporating a logical condition for an object that is entering a region in motion

I am currently in the process of developing a new game concept. The goal of the game is to maneuver a square across the screen while avoiding raindrops that fall from the top of the canvas. I need assistance with programming the logic so that when a rain ...

Tips on resolving the flickering issue in dark mode background color on NextJS sites

One problem I am facing is that Next.js does not have access to the client-side localStorage, resulting in HTML being rendered with or without the "dark" class by default. This leads to a scenario where upon page reload, the <html> element momentari ...

Extension Overlay for Chrome

I'm currently working on developing a Chrome extension, but I'm encountering some confusion along the way. Despite researching online, I keep receiving conflicting advice and haven't been able to successfully implement any solutions. That&ap ...

Having difficulties with JavaScript's if statements

I'm facing an issue with my JavaScript code that is meant to modify the value of a price variable and then display the updated price. The problem arises when I have multiple select options, as the price only reflects the ID of the last statement. Here ...

Implementing the v-select dropdown feature to set a default value

Currently, I am working on a dropdown feature using the v-select component with options for "US" and "CANADA". The challenge I am facing is that even though my customer.country_code value is set to "US", the default selection in the dropdown does not refl ...

Mobile Chrome allows users to utilize the IFrame player API for enhanced video

Currently, I am working on creating a mobile website where I plan to include some YouTube videos using the IFrame player API (https://developers.google.com/youtube/iframe_api_reference). My main goal is to have the video start playing only after the user ...

Some screens struggle with the width of the Ionic toolbar

My ionic app displays a toolbar with icons that appear unevenly spaced on the screen. The issue becomes more pronounced when viewed on smaller width mobile devices: I would have expected the Ionic framework to handle this problem, as it is designed to ass ...

Are there any creative methods for structuring Node.js Alexa code efficiently?

I'm looking for a more organized approach to managing my Node.js Alexa code. With the increasing number of intents in my interaction model, the lines of code in my lambda's index.js have become difficult to manage. Can someone provide an example ...

Error occurred in child process while processing the request in TypeScript: Debug Failure encountered

I encountered the following error in TypeScript while running nwb serve-react-demo: Child process failed to handle the request: Error: Debug Failure. Expression is not true. at resolveNamesWithLocalCache (D:\Projects\react-techpulse-components& ...

System CSS modules do not work correctly with Reactjs, CRA, TS, and Carco when using Less

Issues have arisen with the CSS module system in my project. Below are snippets from various code files and configurations: react-app-env.d.ts, craco.config.js, CircleButtonWithMessage.module.less, CircleButtonWithMessage.tsx, as described below: //react-a ...