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

Top comments (0)