Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change time in embedded youtube video when a button is clicked

I want to embed a youtube video and provide buttons which, when you click them goes to a specific time in the video and resumes playing from there. I've tried using jquery and changing the "src" attribute, like so:

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 when I clicked the button.

Link to image of what I'm thinking: http://i.imgur.com/sCFZSIn.png. Clicking the buttons should make the video jump to the time specified.

like image 694
Lightvvind Avatar asked Oct 08 '14 12:10

Lightvvind


1 Answers

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

Basically, once your iframe loads, the JS API will call onYouTubeIframeAPIReady(), where you construct a YouTube player object. Then you can use that player reference to control the video, such as player.seekTo().

You can still use your iframe, as described at the botton of this section:

As mentioned in the Getting started section, instead of writing an empty element on your page, which the player API's JavaScript code will then replace with an element, you could create the tag yourself.

...

If you do write the tag, then when you construct the YT.Player object, you do not need to specify values for the width and height, which are specified as attributes of the tag, or the videoId and player parameters, which are are specified in the src URL.

The piece your code is missing is the YT.Player object, which you must construct in the callback method mentioned above. This provides access to 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 is in the root scope (like in your head tag) instead of putting it in an onLoad handler.

like image 142
JstnPwll Avatar answered Nov 02 '22 05:11

JstnPwll