DEV Community

Cover image for Common JavaScript "event Handler" Mistake
sagar
sagar

Posted on

Common JavaScript "event Handler" Mistake

When i was dealing javacript click event i was doing this mistake see the blow javascript & jquery code snippet

javascript code example

let name = 'herry';

document.getElementbByClassName('demo').addEventListener('click',function(){
  name = "joy";
})

console.log(name) // herry
Enter fullscreen mode Exit fullscreen mode

jquery code example

let name = 'herry';

$('.demo').on('click',function(){
  name = "joy";
})

console.log(name) // herry
Enter fullscreen mode Exit fullscreen mode

Both javascript & jquery code are same

Mistake i was doing

I was trying to update and access it ‘name’ variable after click event triggered as you can see in the above code
when console.log(name) outside the click variable name printed as herry but it was supposed to be as joy

Why name Doesn't Update Immediately

The behavior of the click event is asynchronous due to this behavior the code lines executed as

  1. let name = ‘herry’;
  2. console.log(name);
  3. $(‘.demo’).on(‘click’,function(){ name = “joy”; })

Order of Execution: JavaScript executes the code sequentially from top to bottom. When console.log(a); is executed, the click event hasn't happened yet, so name is still 'herry'.
Asynchronous Event Handling: The click event handler is an asynchronous operation. It only runs when the user clicks on the element with class .demo. Until the click event happens, the code inside the event handler does not run.

If you want to see the updated value of a after the click event, you should log a inside the click handler:

let name = 'herry';

$('.demo').on('click',function(){
  name = "joy";
 console.log(name) // joy
})
Enter fullscreen mode Exit fullscreen mode

another way

let name = 'herry';

$('.demo').on('click',function(){
  name = "joy";
  UpdateValue(name);
})
function UpdateValue(name){
  console.log(name) // joy
}
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

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

Okay