DEV Community

Cover image for Preventing key-delay in TextArea Element Using Event
Lucretius Biah
Lucretius Biah

Posted on • Edited on • Originally published at kudadam.com

Preventing key-delay in TextArea Element Using Event

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 event.target.value, this code is the code that returns the content in the element. Now when the contents are returned with event.target.value 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 =>{
    console.log(e.target.value);
    console.log(e);
}
Enter fullscreen mode Exit fullscreen mode

A gif debugging the problem

When the first character is entered, the event.target.value is '', this is because, the value is contained in the event object not the event.target.value.
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 event.target.value which also contains the 'already' text, so the function will now be like this

    const get_value = (e){
        let text = e.target.value + e.key
    }
Enter fullscreen mode Exit fullscreen mode

So, that's the solution folks.

Top comments (0)