Search code examples
javascripteventsdom-eventsmouseevent

Attaching listeners to body doesn't work?


I can't figure out why this piece of code isn't working:

<!DOCTYPE html>
<html><head></head><body onload="
document.body.addEventListener('mousedown',function(e){
alert(123);
},false);
"></body></html>

There isn't even any error whatsoever.. it just does nothing.

amazingly if I change 'mousedown' to 'keydown' it works

   <!DOCTYPE html>
    <html><head></head><body onload="
    document.body.addEventListener('keydown',function(e){
    alert(123);
    },false);
    "></body></html>

(I'm using Chrome btw)


Solution

  • The value of this in listeners attached to the body element behaves a little differently in different browsers. Try the following in Firefox and an older version of IE (note that it's specifically for this case, it isn't meant to be a general "what is this?" function):

    <head>
    <title>Some "this" tests</title>
    
    <script type="text/javascript">
    
    var whatIs = (function(global) {
      return function(that) {
    
        // If String(that) isn't useful, try some stuff
        if (String(that) == '[object]') {
          if (that == global || that == window) {
            alert('window');
          } else if (typeof that.tagName == 'string') {
            alert(that.tagName);
          } else {
            alert(that);
          }
    
        // Otherwise show that
        } else {
          alert(that);
        }
      }
    })(this);
    
    </script>
    </head>
    <body onclick="whatIs(this);"  onload="whatIs(this);">
      <div onmousedown="whatIs(this)">this</div>
    </body>
    

    In all browsers, the onload shows window and clicking on the div show this as the div. Clicking on the body shows this to be window in Firefox but the body element in IE, Opera and Chrome.