I want to seek in youtube embed videos, but I have severals videos.
- I launch Video-A on startup
- I have a menu with 2 seek function
- Link A seek on Video-A
- Link B seek on Video-B
So I need to check which video is playing before to seek:
If video id match ==> seek
Else ==> load a new video in the player + seek (when new video is loaded and playing)
Here is my code:
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type='text/javascript' src="https://www.youtube.com/iframe_api"></script>
<script type='text/javascript'>
function onYouTubeIframeAPIReady() {
var player;
player = new YT.Player('player', {
videoId: 'JP9-lAYngi4',
height: '405',
width: '720',
playerVars: { 'autoplay': 1},
events: { 'onStateChange': onPlayerStateChange }
})
function onPlayerStateChange(event) {
if(event.data === 1) {
//alert('playing');
}
if (event.data == YT.PlayerState.PLAYING) {
var url = event.target.getVideoUrl();
// "http://www.youtube.com/watch?v=gzDS-Kfd5XQ&feature=..."
var match = url.match(/[?&]v=([^&]+)/);
// ["?v=gzDS-Kfd5XQ", "gzDS-Kfd5XQ"]
var videoId = match[1];
//alert(videoId)
$('#linkok').click(function(){
if(videoId == "JP9-lAYngi4") {
//alert("same as onload:" + videoId);
player.loadVideoById("x9Us_jMV8hA");
//alert("new video loaded: x9Us_jMV8hA")
}
else {
alert("not the same:" + videoId)
}
});
};
};
};
</script>
My video div and menu:
<div id="video"></div>
<a href="javascript:;" onClick="player.playVideo();player.seekTo(60);">ON CLICK SEEKTO 60s in Video-A</a><br>
<a href="javascript:;" onClick="player.playVideo();player.seekTo(120);">ON CLICK SEEKTO 120s in Video-B</a><br>
My code is not well done, and not really working as I was expecting
Can you please help me make better?
Thanks in advance
I managed to do it like that, but please let me know how to simplify this code: