0

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";
      }
}
1
  • Worth mentioning: assigning directly to onload and onmouseover is kind of brittle. If you or any other code ever want to add a second handler, the first one is lost. Consider using addEventListener (or attachEvent in IE), or using a library like jQuery which handwaves the problems away. Commented Sep 18, 2011 at 21:38

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.