0

I have multiple bootstrap modals with youtube videos and I want to pause not stop when modal its closed. I've searched but couldn't find a good solution that works. As soon as i close the modal and open again the video starts from the beginning. My code is

$(document).ready(function() {
  $('.modal').each(function() {
    var src = $(this).find('iframe').attr('src');

    $(this).on('click', function() {

      $(this).find('iframe').attr('src', '');
      $(this).find('iframe').attr('src', src);

    });
  });
});


function checkForYoutubeVideos(){
            if ( jQuery('.youtubeplayer').length ){
                players = {};
                var tag = document.createElement('script');
                tag.src = "https://www.youtube.com/iframe_api";
                var firstScriptTag = document.getElementsByTagName('script')[0];
                firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
            }
        }
        function onYouTubeIframeAPIReady(e){
            jQuery('iframe.youtubeplayer').each(function(i){
                var youtubeiframeClass = jQuery(this).attr('id');
                players[youtubeiframeClass] = new YT.Player(youtubeiframeClass, {
                    events: {
                        onReady: onPlayerReady,
                        onStateChange: onPlayerStateChange,
                        onError: onPlayerError
                    }
                });
            });
            pauseFlag = false;
        }
        function onPlayerError(e){
            var videoTitle = e['target']['B']['videoData']['title'];
            ga('send', 'event', 'Error', 'Youtube API', videoTitle + ' (Code: ' + e.data + ')', {'nonInteraction': 1}); //Log the API error
        }
        function onPlayerReady(e){
           //Do something when player is ready.
        }
        function onPlayerStateChange(e){
            var videoTitle = e['target']['B']['videoData']['title'];
            if ( e.data == YT.PlayerState.PLAYING ){
                ga('send', 'event', 'Youtube', 'Play', videoTitle);
                pauseFlag = true;
            }
            if ( e.data == YT.PlayerState.ENDED ){
                ga('send', 'event', 'Youtube', 'Finished', videoTitle, {'nonInteraction': 1});
            } else if ( e.data == YT.PlayerState.PAUSED && pauseFlag ){
                ga('send', 'event', 'Youtube', 'Pause', videoTitle);
                pauseFlag = false;
            }
        }
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<div class="bs-example">
  <a href="#videoModal2" target="_blank" class="ga_track wp-read" data-toggle="modal">WATCH VIDEO &nbsp; <span class="next-arrow"></span> <span class="next-arrow"></span></a>

  <!-- Modal HTML -->
  <div id="videoModal2" class="modal fade">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        </div>
        <div class="modal-body">
          <iframe class="youtubeplayer" width="100%" height="315" src="https://www.youtube.com/embed/..." frameborder="0" allowfullscreen></iframe>
        </div>
      </div>
    </div>
  </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
Joe
  • 25
  • 1
  • 1
  • 6

1 Answers1

1

based on this answer. You must use the youTube iframe api. To use it first you must enable it by adding &enablejsapi=1 at the end of the iframe query string in the link. Example:

<iframe width="560" height="315" class="youtubeplayer" id="youtubeplayer" src="https://www.youtube.com/embed/34Na4j8AVgA?list=PLDcnymzs18LWrKzHmzrGH1JzLBqrHi3xQ&enablejsapi=1" frameborder="0" allowfullscreen></iframe>

Next you need to use bootstrap modal event "shown.bs.modal" & "hidden.bs.modal", to check when the modal is open and when is close.

Then i created a function "toggleVideo" that send a message to the iframe, this is how you communicate to youTube API when embedding the iframe manually. The "postMessage" is an HTML5 Feature, Most modern browsers support postMessage, though Internet Explorer 7 does not support it.

$(document).ready(function() {
    $('.modal').each(function() {
        $this = $(this);
        $this.on('shown.bs.modal', function() {
            toggleVideo('playVideo', $(this));
        });

        $this.on('hidden.bs.modal', function(){
           toggleVideo('pauseVideo', $(this));
        })
   });

    function toggleVideo(state, div) {
        var iframe = div.find("iframe")[0].contentWindow;
        iframe.postMessage('{"event":"command","func":"' + state + '","args":""}', '*');
    }
});  
Community
  • 1
  • 1
Web Steps
  • 334
  • 2
  • 11
  • Thanks for this however when I add another modal in the same page it stops from working and sometimes it plays the same video when you click to open modal. – Joe Jan 26 '17 at 06:27
  • I updated the script to support multiple modal with video – Web Steps Jan 27 '17 at 07:16
  • Hi what if I want to add GA tracking events I'm using the edited code above but it is not tracking any events Any suggestions? – Joe Jan 28 '17 at 06:32