Common JavaScript event Handler Mistake

sagar karotiasagar karotia
2 min read

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

jquery code example

let name = 'herry';

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

console.log(name) // herry

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 ImmediatelyThe 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
})

another way

let name = 'herry';

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

0
Subscribe to my newsletter

Read articles from sagar karotia directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

sagar karotia
sagar karotia

I am a passionate frontend developer