Preventing Key Delay In TextArea Using Event

Preventing Key Delay In TextArea Using Event
3 min read Sun May 16 2021

Whiles working with the textarea element today, I found a problem

The problem…

I was using the onkeypress event to grab the text from the textarea element but I realized that the data collected was one character delayed. I then tried the onkeyup and onkeydown but it was still one character delayed.

Initially, I thought this was a bug with my code but after a careful consideration, I realized my code was fine and the onkeypress event was also working correctly so why the one character delay?
A gif showing the problem

What was really happening

When ever we want to get the value of an element from an event, what we normally do is to take the, this code is the code that returns the content in the element. Now when the contents are returned with code, it returns everything excluding the current event, that means, excluding the current character.

We are going to run an experiment to show what is happening. In the gif below, we add a function to the textarea onkeypress event.

const show = (e) => {

A gif debugging the problem
When the first character is entered, the is ”, this is because, the value is contained in the event object not the
This same analogy happens as we continue to type

Solving the problem…

Now as we are seeing what is the causing the problem, we can see the solution,
to prevent the key delay, we just need to adjust our function to add event.key which contains the current character to which also contains the ‘already’ text, so the function will now be like this

	const get_value = (e){
		let text = + e.key

So, that’s the solution folks.

Share this article