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:
Just remove the
()
and you assign thehi
-function to theonclick
-handler.Currently you are assigning the RESULT of
hi()
to theonclick
-handler.You can do
or
You need to say:
Otherwise it will call the
hi()
function other than setting itonclick
.Another way to do this is:
You need to put your function call
hi()
into an anonymous function :Try this:
Notice how I removed the
()
from the assignment. You were calling the function immediately on load.