Reputation: 154
var goldCounter = document.getElementById("goldcounter");
var goldGenerator = document.getElementById("goldgenerator");
var gold = 0;
var goldperclick = 1;
goldCounter.innerHTML = 0;
function goldclick() {
goldCounter.innerHTML = gold + goldperclick;
}
goldGenerator.addEventListener("click", goldclick());
I used this JS code to try to set the text of my HTML paragraph to the value of gold every time the button is clicked, but the text stays at 1. Why?
Thanks everyone it works now! :D
Upvotes: 3
Views: 64
Reputation: 5472
Change this
goldGenerator.addEventListener("click", goldclick());
to this
goldGenerator.addEventListener("click", goldclick);
You want to pass goldClick
as a callback, not the result of the function call.
Upvotes: 1
Reputation: 12747
You're calling the function and passing the result of that to the handler. You need to just pass the function without calling it.
You also need to actually increment the gold you're looking for, otherwise it's always innerHTML = 0 + 1
.
function goldclick() {
gold += goldperclick;
goldCounter.innerHTML = gold;
}
and
goldGenerator.addEventListener("click", goldclick);
should work.
Upvotes: 3
Reputation: 4302
You have to increment the gold variable. It is always at 1 because you are assigning the result of the addition to the element.
function goldclick() {
//Add this
gold += goldperclick;
goldCounter.innerHTML = gold
}
Upvotes: 2
Reputation: 45242
There is a problem in this line:
goldGenerator.addEventListener("click", goldclick());
It should be
goldGenerator.addEventListener("click", goldclick);
You should be passing the function goldclick
into addEventListener
.
What your code is currently doing is calling goldclick
, and passing the result of this function into addEventListener
.
Upvotes: 1