I\'m relatively new to JS, but I have programmed in C before, and I\'m trying to get my head around the whole event driven nature of it. I\'m trying to create a script that
yes your javascript function will call only when page will load .If you also want to call that init() function on click Test button so please try like this :
JavaScript:
function init(){ alert("hello"); }
window.onload = init;
HTML:
<button id="test" onClick='init()'>Test</button>
That's not right, it should be:
function init(){
document.getElementById("test").onclick = function () { alert("hello"); };
}
This is because you need in JavaScript you need to assign the function itself to the click
event (alert is a function).
Take this for example:
function hello() {
alert("hello");
}
document.getElementById("test").onclick = hello;
Note that I didn't put the brackets ()
after hello
function? That's because I'm using a reference to the function itself. If I put the brackets, I'm actually evaluating that function at the point in time of the click assignment happening.
So doing:
document.getElementById("test").onclick = hello();
Will show the alert will show the alert
immediately after this line has been executed.