Change time in embedded YouTube video on button click

I want to embed a YouTube video and provide buttons that when you click on them will jump to a specific time in the video and resume the game from there. I tried using jquery and change the "src" attribute like:

Original source:

<iframe src="http://www.youtube.com/embed/PjDw3azfZWI?&t=5m30s&rel=0&amp">

      

JS:

$("#link1").click(function() {
    $("#video").attr("src", "http://www.youtube.com/embed/PjDw3azfZWI?&t=10m30s&rel=0&amp");
});

      

This caused the browser to refresh on button click.

Link to image of what I think: http://i.imgur.com/sCFZSIn.png . Pressing the buttons should translate the video at the specified time.

+3


source to share


1 answer


You don't have to reload the iframe to manage the video; use Javascript API methods. Check out seekTo here: https://developers.google.com/youtube/iframe_api_reference#Playback_controls

Basically, once your iframe is loaded, the JS API will call onYouTubeIframeAPIReady () where you create the YouTube player object. Then you can use that player's link to control the video, like player.seekTo ().

You can use your iframe as described in botton in this section :

As mentioned in the "Getting Started" section, instead of writing a blank element on your page, which is the player API then the code is replaced with an element, you can create a tag yourself.

...

If you are writing a tag, then when you create a YT.Player object, you do not need to specify the width and height values, which are specified as tag attributes, or the videoview and player parameters, which are specified in the src URL.



Some of your code is missing, it's a YT.Player object that you have to build in the callback method mentioned above. This provides access to the player controls.

Here's a Fiddle demonstrating:

var player, seconds = 0;
function onYouTubeIframeAPIReady() {
    console.log("player");
    player = new YT.Player('player', {
        events: {
          'onReady': onPlayerReady
        }
      });
}

function onPlayerReady(event) {
    event.target.playVideo();
}

function seek(sec){
    if(player){
        seconds += sec;
        player.seekTo(seconds, true);
    }
}

      

You can put this code in a separate script, but make sure it's in the root scope (for example, in the head tag) instead of putting it in an onLoad handler.

+4


source







All Articles