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

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

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

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay