Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
124
rated 0 times [  129] [ 5]  / answers: 1 / hits: 7395  / 10 Years ago, wed, october 8, 2014, 12:00:00

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.


More From » jquery

 Answers
11

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.


[#42017] Tuesday, October 7, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kylanalis

Total Points: 438
Total Questions: 85
Total Answers: 102

Location: Barbados
Member since Sun, Nov 27, 2022
1 Year ago
kylanalis questions
Sat, Oct 2, 21, 00:00, 3 Years ago
Tue, Oct 13, 20, 00:00, 4 Years ago
Thu, Feb 13, 20, 00:00, 4 Years ago
Tue, Jan 7, 20, 00:00, 4 Years ago
;