iOS engineer who likes clean, simple designs and sans-serif.

Loading

Autoplaying Wistia Video in Modal

When a user clicks a link, this code injects the Wistia video into a Modal, opens the Modal and then automatically plays the video. (Requires Foundation Reveal, videos hosted on Wistia and jQuery.)

The Links (HTML):

  <a class="show_preview_video clearfix" data-video_source="https://fast.wistia.net/embed/iframe/lo3xj0qj3t" data-video_title="Scott Roen — American Express" data-video_hash="lo3xj0qj3t">Watch Scott’s video ➝</a>

  <a class="show_preview_video clearfix" data-video_source="https://fast.wistia.net/embed/iframe/5lnydcupe5" data-video_title="Marisa Ricciardi — NYSE Euronext" data-video_hash="5lnydcupe5">Watch Marisa’s video ➝</a>

  <a class="show_preview_video clearfix" data-video_source="https://fast.wistia.net/embed/iframe/i6ir4lcyyj" data-video_title="Matt Haradon — New York Times Company" data-video_hash="i6ir4lcyyj">Watch Matt’s video ➝</a>

The Modal (HTML)

  <div id="video-preview-modal" class="reveal-modal large">
    <header>
      <h2></h2>
      <p class="subhead"></p>
    </header>
    <br>
    <div class="wrapper-with-intrinsic-ratio image-wrapper">
      <iframe id="video-preview-iframe" name="wistia_embed" class="flex-video" src="" frameborder="0" scrolling="no" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>
     
    </div>
    <a class="close-reveal-modal icon-x-circle"></a>
  </div>

The Javascript:

  <script>
    $(document).ready(function(){
      // Loads Correct Video and Plays It On Click
      $(".show_preview_video").click(function(){
        showvideo($(this));
      });

      // Removes the video when modal is closed (to stop it from playing)
        $("#video-preview-modal .close-reveal-modal").click(function(){
        killVideoSource();
      });
    });

    function showvideo(self){
      // Forces Foundation reveal modal to NOT close on a background click
      $("#video-preview-modal").reveal({
        "open": replaceVideoSource(self),
        'closeOnBackgroundClick': false
      });
    }
   
    function replaceVideoSource(self){
      var video_source = self.data('video_source');
      var video_title = self.data('video_title');
     
      // Inject video source from data attributes
      $('iframe#video-preview-iframe').attr('src', video_source);
      $('#video-preview-modal header h2').html(video_title);
      var wistiaEmbed = $("iframe#video-preview-iframe")[0].wistiaApi;

      // Play the video using the Wistia API
      wistiaEmbed.play();
    }

    function killVideoSource(){
      // Remove the video source to stop the video
      $('iframe#video-preview-iframe').attr('src', '');
    }
  </script>
  <script src="https://fast.wistia.net/static/iframe-api-v1.js"></script>

Leave a Comment