Search code examples
javascriptdom-events

Why can't I assign a function directly?


This code calls the f() function:

<p id="firstp">Hello!</p> 
<script>
  function f() {
    doSomething();
  };
  document.getElementById("firstp").onmouseover = function() {
      f();
  };
</script>

Yet if I write it this way, it stops working:

  document.getElementById("firstp").onmouseover = f();

Why doesn't the event handler get set when I call the function directly?


Solution

  • Because you don't want to call the function, you want just to tell the browser that it should call it when mouseover event happens. f() (round brackets after function's name) calls the function and assigns to .onmouseover what f returns. You want to assign the reference to f to .onmouseover, so what you are looking for is

    document.getElementById("firstp").onmouseover = f;