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

2 2

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay