title: How to run code only when iframe loaded
body: <p>I have been battling with this issue for a few days now and finally found a partial solution but I think it could be improved.</p>
  
  <p>In my project, I have a series of <code>iframe</code>s that contain videos. When a link is clicked are displayed with a slide transition and when the link is clicked again the video stops and the <code>span</code> containing the <code>iframe</code> is hidden also with a transition. </p>
  
  <p>This is achieved by adding and removing a css class of "open" that has a height and a transition in it. In addition to this I have an event listener that collapses the containing span also when the video finishes. All this works fine and to save time I am not posting the code.</p>
  
  <p>The issue I was having was with slow page loading times, so I removed the <code>src</code> attribute for the <code>iframe</code>s from the html and moved it to my js file and assigned it only after the click is performed. This wasn't working and I realised I needed the <code>iframe</code> to fully load before running the rest of the code inside the "click" method. So I delayed this part of the code by 100ms. </p>
  
  <p>All this works, but I feel it would be better to have the rest of the code run not after a 100ms lapse but when the <code>iframe</code> is loaded (in case page viewed by slower computers). Not sure how to do this.</p>
  
  <p>Here is the code as it stands now:</p>
  
  <pre><code>var player;
  var frame = $("#frame");
  
  
  frame.bind("load", function () {
      player = $(this).contents().find("#myVid");
      player.on('ended', function () {
          frame.removeClass("open");
      });
  });
  
  $("#clickableLink").click(function(){
  
  
          if (frame.hasClass("open")) {   
  
              frame.removeClass("open");
              frame.contents().find('#myVid').get(0).pause();
  
          } else {
  
              function delayed(){
  
                  frame.addClass("open");
                  frame.contents().find('#myVid').get(0).play();
  
              }
              frame.attr("src","iframe.html");
              setTimeout(delayed, 100);
          }
  
  
  });
  </code></pre>
  
  <p>Fairly new to development so I am looking for the simplest way to do this. Any help appreciated.</p>