Reputation: 5
Why when I add an event as a function like this:
function func(arg)
{
arg.style.marginLeft = "65px";
}
window.onload = function() {
var test = document.getElementById("aaa");
test.onmouseover = func(test);
}
It's been executed immediately (even if I do not hover the element).
But this one works:
window.onload = function() {
var test = document.getElementById("aaa");
test.onmouseover = function() {
test.style.marginLeft = "65px";
}
}
Upvotes: 0
Views: 65
Reputation: 413996
You're setting the "onmouseover" property to the return value of a function call expression:
test.onmouseover = func(test);
That "func(test)" calls the function "func()", just as it would in any other code.
You could instead do this:
test.onmouseover = func;
That will bind the event handler and not call "func()", but it won't arrange for the additional parameter to be passed. edit Oh wait that's just the DOM element itself.
Upvotes: 3