vistajess
vistajess

Reputation: 687

Global Variable doesn't update onclick function

I have 2 buttons bound with a function that will update a global variable. Why do I have to click the button twice so then it'll update said global variable? https://jsfiddle.net/q9akn3gz/1/

<button id="btn1" onclick="myFunc()"> 1 </button>
<button id="btn2" onclick="myFunc()"> 2 </button>

 

var val = 0;
document.querySelector('#btn1').addEventListener('click',function() {
    val = 200;
});
document.querySelector('#btn2').addEventListener('click',function() {
    val = 400;
});
function myFunc() {
    console.log(val);
}

Upvotes: 1

Views: 3570

Answers (3)

A. Burak Erbora
A. Burak Erbora

Reputation: 1064

You are calling the function first and updating later. Your function prints to the console Before updating the value. Try moving the value update to the same function with console.log(val) and using the value operation before that line.

<button id="btn1" onclick="myFunc(200)"> 1 </button>
<button id="btn2" onclick="myFunc(400)"> 2 </button>

var val = 0
function myFunc(value) {
   val = value;
   console.log(value);
}

Upvotes: 1

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174967

The reason is that the onclick attribute was encountered before the addEventListener call, so it runs first, so you log first, then update.

It's considered bad practice to use onclick handlers with global functions, please stick to addEventListener.

Upvotes: 2

gurvinder372
gurvinder372

Reputation: 68393

remove the onclick attribute event handler, and call the same method in dynamically assigned event handler

check this updated fiddle

<html>
<body>
<button id="btn1">
1
</button>
<button id="btn2">
2
</button>

<script>
var val = 0;
 document.querySelector('#btn1').addEventListener('click',function() {
  val = 200;
  myFunc();
 });
 document.querySelector('#btn2').addEventListener('click',function() {
  val = 400;
  myFunc();
 });
function myFunc() {

 console.log(val);
}
</script>
</body>
</html>

Upvotes: 1

Related Questions