html:
<button id="go-btn">GO BUTTON!</button>
javascript:
function hi(){
alert("hi");
}
document.getElementById("go-btn").onclick = hi();
When I refresh the page the alert pops up before I click the button. Why is this happening? Thanks a lot!
Because you are calling it while the assignment:
document.getElementById("go-btn").onclick = hi();
Just remove the ()
and you assign the hi
-function to the onclick
-handler.
document.getElementById("go-btn").onclick = hi;
Currently you are assigning the RESULT of hi()
to the onclick
-handler.
Try this:
function hi(){
alert("hi");
}
document.getElementById("go-btn").onclick = hi;
Notice how I removed the ()
from the assignment. You were calling the function immediately on load.
You need to say:
document.getElementById("go-btn").onclick = function(){hi();}
Otherwise it will call the hi()
function other than setting it onclick
.
Another way to do this is:
document.getElementById("go-btn").onclick = hi;
You can do
var hi = function(){
alert("hi");
}
document.getElementById("go-btn").onclick = hi();
or
document.getElementById("go-btn").onclick = hi;
You need to put your function call hi()
into an anonymous function :
document.getElementById("go-btn").onclick = function() {hi()};