in Javascript, to associate a given function with an event via script, you must use syntax like this:
someFunc()
{
//do something
}
window.document.body.onclick = someFunc
The important thing to note is that in the line above, there are no ()'s after someFunc. The reasoning behind this is, javascript will execute whatever is on the right of the equals sign, this is because in JS, functions can be treated ad data. Suppose you wanted to pick a random event handler for your onclick event. You could use something like this:
function randomHandler()
{
//do something and define rndmhdnler as
//a function reference
return rndmhdnler
}
window.document.body.onclick = randomHandler()
it immediately, before any click occurs (whenever the intrepreter first sees the line above) runs randomHandler and returns a function reference.
This is just an example of one event handler you can register.So remember don't use ()'s unless you want the code to be run immediately.
Note: Above applies only when setting the events in a script block. If you define them inline like:
<img onmouseover="someFunc()">
notice the ()'s are there - strange, but that's just the way it is.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.