title: Detect event from iframe works with jQuery event listener on parent, but now with pure JS
body: <p>I'm trying to find a few different ways to add event listeners to listen to custom events coming in from an iFrame. </p>
  
  <p>I can successfully listen to the event coming from the iFrame using jQuery event listener, but I can't seem to do the same with pure JS. If anyone is willing to take a look at the code and let me know what I'm doing wrong, that would be splendid.</p>
  
  <h3>Inside iFrame</h3>
  
  <pre><code>  (function(i,s,o){
      // trigger load event for parent of iframe
      parent.$('body').trigger('myevent:load');
  
      // also trigger when everything is loaded, again
      window.onload = function() {
        parent.$('body').trigger('myevent:load');
      }
    })(window,document,$);
  </code></pre>
  
  <h3>Iframe container (parent)</h3>
  
  <pre><code>&lt;script type="text/javascript"&gt;
  &lt;!--
  
  // iFrame document resize script
  function autoResize(id){
    var newheight
      , newwidth
      , iframe;
  
    if(document.getElementById){
      iframe = document.getElementById(id);
      newheight=iframe.contentWindow.document .body.scrollHeight;
      newwidth=iframe.contentWindow.document .body.scrollWidth;
    }
  
    iframe.height= (newheight) + "px";
    iframe.width= (newwidth) + "px";
  };
  
  // add event cross browser
  function addEvent(elem, event, fn) {
    // avoid memory overhead of new anonymous functions for every event handler that's installed
    // by using local functions
    function listenHandler(e) {
      var ret = fn.apply(this, arguments);
      if (ret === false) {
        e.stopPropagation();
        e.preventDefault();
      }
      return(ret);
    }
  
    function attachHandler() {
      // set the this pointer same as addEventListener when fn is called
      // and make sure the event is passed to the fn also so that works the same too
      var ret = fn.call(elem, window.event);
      if (ret === false) {
        window.event.returnValue = false;
        window.event.cancelBubble = true;
      }
      return(ret);
    }
  
    if (elem.addEventListener) {
      elem.addEventListener(event, listenHandler, false);
    } else {
      elem.attachEvent("on" + event, attachHandler);
    }
  }
  
  // listen for load event from iFrame
  addEvent(document, 'myevent:load', function(){
    // doesn't work
    console.log("IFRAME LOADED! 2");
  });
  
  document.addEventListener('myevent:load', function(){
    // also doesn't work
    console.log("IFRAME LOADED! 1");
  });
  
  $(document).bind('myevent:load', function(){
    // works
    console.log("IFRAME LOADED! - jQuery");
  });
  
  //--&gt;
  &lt;/script&gt;
  </code></pre>