YouTube iframe API - pause video in modal onblur

From Metro Studios Knowledgebase

Jump to: navigation, search


[edit] To Start

Insert <div id="player"></div> into your markup wherever you want the iframe to go. This div element will be replaced by an iframe when the following script runs:

<script type="text/javascript">

var tag = document.createElement('script');
tag.src = "//";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var player;
function onYouTubeIframeAPIReady() {
        player = new YT.Player('player', {
            height: '360',
            width: '640',
            videoId: 'ZL04sVhrGRM',
            playerVars: {'rel': 0}

    // functions to pause, play, whatever


Height and width are both ints within single quotes representing the initial height and width of the iframe. Do not add 'px' like with CSS.
videoId - google it if you're not sure
playerVars - this is an object whose only key/value right now is for related videos, and is set to false (0) so no related videos are shown on pause, or at the end of the video

[edit] The Magic

What the script above does, is replace the div id="player" element with an iframe that is accessible with the YouTube API. The first line of the onYouTubeIframeAPIReady() function is a constructor that creates a YT.Player object named player. This is what allows us to pause, or manipulate the video with javascript. Without this, the next part would not work.

In the commented line you see in the script above, place this function to pause the video:

    $('.modal').on('', function(){
        // var html = $('#video-modal').html();
        // $('#video-modal').empty().append(html);

[edit] Notes

This function is for a bootstrap modal in particular and is executed when the modal is given the classes. player.pauseVideo() pauses the video.

[edit] References

YouTube Player API Reference [1]

Personal tools
Wiki Navigation