Reputation: 443
I want the function to run only once on the first click and no more. But I get an error that someVar
is not defined, that is what I have included in the condition. Why is it giving the error? How to solve this?
button.onclick = function () {
if (someVar == undefined) {
console.log("Hi");
someVar = 1;
}
}
Upvotes: 0
Views: 44
Reputation: 5863
this
approach (this
references to onClick
function
):
const button = document.querySelector('button')
button.onclick = function () {
if (this.someVar == undefined) {
console.log("Hi");
this.someVar = 1;
}
}
<button>button</button>
Global variable approach:
const button = document.querySelector('button')
let someVar = undefined;
button.onclick = function () {
if (someVar == undefined) {
console.log("Hi")
someVar = 1;
}
}
<button>button</button>
Upvotes: 2
Reputation: 341
Have you defined the someVar as a global Variable? use it like this =>
var someVar = undefined;
button.onclick = function () {
if (this.someVar == undefined) {
console.log("Hi");
this.someVar = 1;
}
}
Upvotes: 1