views:

203

answers:

2

In the code HTML+Script below,

  • an event handler is attached after page load using setAttribute(...).
  • The event hander is passed an argument which is read dynamically too.
  • the event hander is attached successfully ( verified by a getAttribute(...)

However, the handler does not fire.

What is wrong with the snippet below?

<HTML>
 <BODY onload="loader();">
   <table>
     <tbody>
      <tr>
       <td id="myId">FirstColumn</td>
       <td id="otherId">SecondColumn</td>
       <td id="lastId">Balderdash</td>
      </tr>
     </tbody>
   </table>
 </BODY>
 <script language="javascript">
    function loader(){

    document.getElementById('myId').setAttribute('onmouseover','showMessage("'+document.getElementById('otherId').innerHTML+'");');
    alert(document.getElementById('myId').getAttribute('onmouseover'));

    document.getElementById('myId').setAttribute('onmouseout','alert(\"'+document.getElementById('otherId').innerHTML+'\");');
    alert(document.getElementById('myId').getAttribute('onmouseout'));
    document.getElementById('lastId').setAttribute('onmouseout','alert("hohoho");');

    alert(document.getElementById('lastId').getAttribute('onmouseout'));
    function showMessage( aMessage ){
     alert(aMessage);
    }
 </script>
</HTML>
+1  A: 

Do not use setAttribute to set event handlers on DOM nodes. Just use the event handler property direct, and assign it a function rather than a string:

document.getElementById('myId').onmouseover = function() {
  showMessage(document.getElementById('otherId').innerHTML);
};
Tim Down
Two questions - - IIRC the handler doesn't have to be an anonymous function; y/n?- Doesn't the argument passed need to be escaped?
Everyone
Correct, the handler does not have to be an anonymous function. Second, I didn't focus so much on the escaping part of the question, but I assume that bit's no longer a problem?
Tim Down
A: 

Tim's post up there helped me figure it out; albeit my understanding is empirical.

In addition to making a direct assignment

e.g.

document.getElementById(...).onMouseOver = stuff;
function stuff(){//do the Deed};

in lieu of

document.getElementById(...).setAttribute(...);

Apparently the event handler attached may not accept any argument.

I changed my handler signatures to accept 0 arguments, and it works!

Everyone
No, in non-IE browsers your event handler functions will be passed an event object, which can be extremely useful. In IE you have to access the event via window.event. For example: el.onmouseover = function(evt) { evt = evt || window.event; /* Do stuff with event object */ };
Tim Down
Ty (+: that is usefulAt the moment we're looking purely at IE though
Everyone