Make callback after pressing play button - Youtube embed video

Is it possible to execute javascript action after clicking play button? I know that I will need to use the YStube API function of the onStateChange form. But I really don't know where to start? Any help? Thank.

-

I also found something here: http://apiblog.youtube.com/2011/01/introducing-javascript-player-api-for.html

+5
source share
4 answers

Here is a solution that you can easily expand: http://jsbin.com/evagof

+7
source
+4
    <script src="http://www.google.com/jsapi" type="text/javascript"></script>
    <script type="text/javascript">
      google.load("swfobject", "2.1");
    </script>    
    <script type="text/javascript">
      // Update a particular HTML element with a new value
      function updateHTML(elmId, value) {
        document.getElementById(elmId).innerHTML = value;
      }


      // This function is called when the player changes state
      function onPlayerStateChange(newState) {
        updateHTML("playerState", newState);
        if(newState === 1){
            //if the player is now playing
            //add your code here
        }
      }

      // This function is automatically called by the player once it loads
      function onYouTubePlayerReady(playerId) {
        ytplayer = document.getElementById("ytPlayer");
        // This causes the updatePlayerInfo function to be called every 250ms to
        // get fresh data from the player
        setInterval(updatePlayerInfo, 250);
        updatePlayerInfo();
        ytplayer.addEventListener("onPlayerStateChange");
      }

      // The "main method" of this sample. Called when someone clicks "Run".
      function loadPlayer() {
        // The video to load
        var videoID = "ylLzyHk54Z0"
        // Lets Flash from another domain call JavaScript
        var params = { allowScriptAccess: "always" };
        // The element id of the Flash embed
        var atts = { id: "ytPlayer" };
        // All of the magic handled by SWFObject (http://code.google.com/p/swfobject/)
        swfobject.embedSWF("http://www.youtube.com/v/" + videoID + 
                           "?version=3&enablejsapi=1&playerapiid=player1", 
                           "videoDiv", "480", "295", "9", null, null, params, atts);
      }
      function _run() {
        loadPlayer();
      }
      google.setOnLoadCallback(_run);
    </script>
<div id="videoDiv">Loading...</div>
<p>Player state: <span id="playerState">--</span></p>

http://code.google.com/apis/ajax/playground/?exp=youtube#polling_the_player

+3

All Articles