Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fire an event on play of youtube iframe embed

I need to fire an event on play of a youtube iframe. So when the play button is pressed I need to call a function to hide the span.module-strip

I've tried this but maybe I'm going down the wrong path?

$("#home-latest-vid")[0].onplay = function() {
    alert('hi');
};

HTML:

<div class="module module-home-video">

    <span class="module-strip">Latest Product Video</span>

        <iframe id="video" src="http://www.youtube.com/embed/RWeFOe2Cs4k?hd=1&rel=0&autohide=1&showinfo=0&enablejsapi=1" frameborder="0" width="640" height="360"></iframe>
</div>
like image 448
Rob Morris Avatar asked Jun 04 '14 14:06

Rob Morris


2 Answers

player.getPlayerState():Number Returns the state of the player.

https://developers.google.com/youtube/iframe_api_reference

 /* 
      * player.getPlayerState():Number
      *
      * -1 – unstarted
      *  0 – ended
      * 1 – playing
      *  2 – paused
      *  3 – buffering
      *  5 – video cued
      *
      */
      function checkIfPlaying(){
        var playerStatus = player.getPlayerState();

         return  playerStatus == 1;
      } 
like image 107
Mohammed Nokri Avatar answered Sep 20 '22 22:09

Mohammed Nokri


  • DEMO: https://so.lucafilosofi.com/fire-an-event-on-play-of-youtube-iframe-embed/
<script src="https://www.youtube.com/iframe_api"></script>

<div class="module module-home-video">
    <span class="module-strip">Latest Product Video</span>
    <div id="video"></div>
</div>

<script>
    var player, playing = false;
    function onYouTubeIframeAPIReady() {
        player = new YT.Player('video', {
            height: '360',
            width: '640',
            videoId: 'RWeFOe2Cs4k',
            events: {
                'onStateChange': onPlayerStateChange
            }
        });
    }

    function onPlayerStateChange(event) {

      if (event.data == YT.PlayerState.PLAYING) {
         alert('video started');
         playing = true;
        }

      else if(event.data == YT.PlayerState.PAUSED){
            alert('video paused');
            playing = false;
       }
}
</script>
like image 29
Luca Filosofi Avatar answered Sep 17 '22 22:09

Luca Filosofi