How to solve 'Event Listener Always One Step Behind'
. Javascript event handler
. Event Listener Always One Step Behind
. Why Event Listener Always One Step Behind
. How to solve Event Listener Always One Step Behind problem
. the use of setTimeout() function
Event Listener Always One Step Behind:
- when we use any keyboard event like `keydown` `keyup`... [except `input` event], the output of the event always one step behind. See in example:
Example-1: Output always shows previous event's value instead of current keypress.
document.querySelector('input').addEventListener('keydown', (evt) =⋗ {
console.log(evt.target.value)
})
Why this happens ?
- when we press any key, that value just taken via event handle but to show that value, that requires another event to fire. because the log is inside the a event handler, and that will only fire when event occurred, so the 2nd event show the value of first's event.
By timer function we can solve this problem:
- when we press any key, first time that value is available but it requires 2nd event to show, so we set the value inside setTimer callback this way setTimeout will be invoke as soon as it times out (that trigger second event), and in setTimeout we set the value 0 seconds, that means immediately timeout.
Summary:
So setTimeout fire event 2nd time, instead user user, which solve the problem.
Example-2: Now it works as it should by.
document.querySelector('input').addEventListener('keydown', (evt) =⋗ {
setTimeout(() =⋗ {
console.log(evt.target.value)
}, 0)
})