← Snippets - Script

iFrame Video in a Modal

Clients will often ask to put iFrame videos inside of modals. This has one particularly interesting issue in that after you close the modal, the video keeps playing. While you can fix that with script that works with YouTube’s API, how do you fix it if the video provider is Vimeo, or some other provider entirely?

This script refreshes the SRC within the modal, causing it to reload, and thus, stop playing. It works for any iFrame video provider.

How To

whatever.mustache

Please note that this should be placed in a script tag, either in the scripts.mustache file or at the bottom of the template mustache for the one that needs it. This is because, if placed in the regular scripts.js, it will run inside the CMS and break the iframe. If placed in the if/else to run outside the CMS, it won’t get run late enough, and so it won’t work.

You can create a function for each modal as needed, to make sure that the right video is being stopped when the modal is closed.

<script>
  $('#modal1').on('hidden.bs.modal', function () {
    var src1 = $('#modal1 .modal-body iframe').attr('src');
    $('#modal1 .modal-body iframe').attr('src',src1);
  });
</script>

Example Sites

  • Forcht Bank (Bootstrap 2. Underneath the hero ad, each of the buttons open a modal which contains an iframe. Script is included at the bottom of the home.mustache file.)
  • Bank of Hope (Bootstrap 3. Link is to Gitlab because the client deleted the page on UAT and never recreated.)
  • 1st United Credit Union (Bootstrap 4. Clicking the image with the play button, in the section underneath the hero ad, opens a modal with an iframe video.)

Tags: bs2, bs3, bs4, youtube, iframe, vimeo, modal, jquery, script, html, mustache