Transfer the scroll top value from a textarea to a div element

In the parent div, there is a div and a textarea. I am attempting to synchronize the scrollTop value of the textarea with the div so that they move together when scrolling.

The issue arises when I input text into the textarea and hit enter for a new line. The div's scrollTop value does not update, while the textarea's does.

Upon hitting enter again, both values update, but it appears that the div's scrollTop value lags one step behind the textarea.

https://codesandbox.io/s/objective-feather-ngq8t

handleScroll = (e) => {
   setTextareaScrollTop(e.target.scrollTop);
   e.target.previousElementSibling.scrollTop = e.target.scrollTop;
   setDivScrollTop(e.target.previousElementSibling.scrollTop);
};

https://i.sstatic.net/woIsT.png

Answer №1

To work around this issue simply, you can omit the setDivScrollTop from the handleScroll function and insert a new line with \n after updating the text in the red div. The caret character will then allow it to align with the other div.

handleScroll = (e) => {
    setTextareaScrollTop(e.target.scrollTop);
    e.target.previousElementSibling.scrollTop = e.target.scrollTop;
    // setDivScrollTop(e.target.scrollTop);
};

handleInput = (e) => {
    console.log(divScrollTop, textareaScrollTop)
    setText(e.target.value + "\n"); // add "\n"
};

This can be observed in action on Codesandbox

Additionally, I have included a border style for the text area element and set spellCheck={false} to display their equality.

Answer №2

I have made some modifications to your code, which you can view at this link.

const useUpdate = () => {
  const [, dispatch] = useState(0);
  const ref = useRef(() => {
    dispatch((v) => v + 1);
  });

  return ref.current;
};

When you need to repaint, simply use the following:

  handleScroll = (e) => {
    e.target.previousElementSibling.scrollTop = e.target.scrollTop;
    refresh();
  };

Instead of using setState, I have replaced it with useUpdate. Let me know your thoughts on this approach, as it deviates slightly from your initial question.

If I remove both instances of setState as you had originally, I encounter the issue you described.

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

Making the height of two divs equal within the same parent element using CSS

Looking for a way to make two adjacent divs, #innerwrapper .sidebar and #innerwrapper > .content, from the same parent container, #innerwrapper, have equal heights due to them being floated left. I initially used jQuery in a separate file to resolve th ...

The homepage is not converting to a different language

Using the WPML plug-in for my WordPress website has been successful in translating most of my pages, but I am running into an issue with the home page. Even though I have manually translated and published the home page, it still does not translate when cli ...

Use JavaScript and PHP to retrieve a value from an array and dynamically populate select options based on that value

In my PHP code, I have two arrays structured like this: Array ( [0] => 11 [1] => 11 [2] => 11 [3] => 11 [4] => 11 [5] => 187 ) Array ( [0] => 118 [1] => 112 [2] => 85 [3] => 81 [4] ...

Google-play-scraper encounters an unhandled promise rejection

I'm trying to use the google-play-scraper library with Node.js, but I keep encountering an error when passing a variable as the 'appId'. How can I resolve this issue? Example that works: var gplay = require('google-play-scraper') ...

Utilizing JQuery Ajax to dynamically replace elements using JQuery functions

My issue is as follows... I am using AJAX and jQuery to populate a form. When the user makes a selection from a dropdown menu, AJAX retrieves data based on the choice and populates the form with this data. Sometimes, new elements are created when the AJA ...

Is it possible to caution users before refreshing the page, while still allowing them to

I have a script that displays a warning message to the user when they attempt to refresh the page. It works perfectly for that purpose. However, my issue is that this same alert pops up when a user clicks on a button or a link within the website itself. I ...

Utilizing Protractor's advanced filtering techniques to pinpoint the desired row

I am trying to filter out the specific row that contains particular text within its cells. This is my existing code: private selectTargetLicense(licenseName: string) { return new Promise((resolve => { element.all(by.tagName('clr-dg-tab ...

Utilizing ASP.NET AJAX: Enhancing User Experience with ScriptManagerProxy for HTML Button Click Events

I am currently working on a solution for the following issue: Managing the client-side click event of a button - preventing postback if the JavaScript call returns false (e.g. onclick="js:return IsThisAllowed()") The JavaScript method will either return ...

Enabling a JSON file property to be clickable as needed

I am working with a JSON file obtained from an API call, which contains various objects. My goal is to display the message property of each object, some of which may contain hyperlinks within the message. Here is the HTML code I have implemented to make t ...

Navigate to a different route in AntD Table by clicking on it

I am currently implementing React Router in my navigation component. My goal is to enable users to navigate from screen Y to screen X when they click on a table element. In the past, I achieved this by using "this" command but it seems that it does not ...

No content sent in the request body while implementing fetch

Attempting to send graphql calls from a React component to a PHP server using the fetch method for the first time. The setup involves React JS on the client-side and Symfony 4 on the server-side. Despite indications that data is being sent in the browser ...

A guide to incorporating a textview into a React application using the Google Maps API

Wondering how to incorporate a textview within a react-google-maps component? Successfully setting up a Google map page in React using the react-google-maps API, I've managed to insert markers and link them with polylines. import React from "react"; ...

The JavaScript function for converting a date to a local string in the format of DD MMM YYYY is causing an error message in the browser console stating that it is not a valid function

I am encountering an issue with formatting a date string. The date is currently in the format 2021-03-31T00:00:00, and I need it to be displayed as 31 Mar 2021. In my TypeScript code, I attempted to use the following function: const formattedDate = i.Susp ...

Utilizing React with Okta authentication, powered by an Express server running behind an

My current setup involves an app with a react client and express backend, which is behind an nginx proxy using SSL. When attempting to authenticate through Okta, I successfully log in but encounter issues when trying to redirect with the code const auth = ...

Do not reveal result of coin flip using Javascript and API

Even though I meticulously copied my professor's parsing process, the display isn't turning out as expected. It seems like something is off in my code. <div class="main"> <p>Heads or tails? click to toss the coin</p> & ...

Regular expressions: understanding greedy versus lazy quantifiers

Imagine this situation: a = 'one\\two\\three.txt'; The desired output is "three.txt". However, the attempted solution of: a.match(/\\(.+?)$/) is unsuccessful. What could be causing this issue? How can we successf ...

What is the best way to send a POST request using axios with both body and form data included at the

Is there a way to successfully send a post request using Axios that includes both body data and form data? I am having trouble getting the data to reach my route handler: axios({ method: 'POST', url: `${keys.SERVER_URL}/post/new-post/${i ...

Guide to dynamically insert rows in HTML using Vue.js based on the selected option

This is the initial row. Depending on the selection made here, different rows will be displayed <div class="row"> <div class="col-md-4"> <div class="form-group label-floating"> <label class="control-label">Case Type< ...

Transform your .obj files into .glb files effortlessly with npm and Laravel

I've hit a roadblock for 2 days now and can't seem to find a solution. Could someone lend me a hand with this? Query: What's the best way to convert a .obj file to .glb? I attempted using obj2gltf npm package but integrating it with Larav ...

What is the best way to export Class methods as independent functions in TypeScript that can be dynamically assigned?

As I work on rewriting an old NPM module into TypeScript, I encountered an intriguing challenge. The existing module is structured like this - 1.1 my-module.js export function init(options) { //initialize module } export function doStuff(params) { ...