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 will validate form input, however all of my code is being run - everything inside if/else, loops, what have you - regardless of the event happening or not. To test, and to make it easier to post here, I've written a simple program that has this problem too.
HTML:
<button id="test">Test</button>
Javascript:
function init(){
document.getElementById("test").onclick = alert("hello");
}
window.onload = init;
From what I understand, the init function should be called when the page loads (window.onload), and the alert should pop up when the button with the ID "test" is clicked (onclick). What is actually happening is that the alert is popping up as soon as the page loads, and will pop up again if I hit the button.
My thinking is that I've made some incorrect assumptions about the order in which JS is executed, but I cant think of what that is. Is anyone able to shed some light on this?
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With