Youtube Embed API Stop, Play and Change Video

Recently I got this feature request that look like : 1 element (as the youtube embed iframe container) at the left and at the right is the youtube video list. The youtube embed video changed if the user click one of the list at the right side. Here is what I do :

HTML code below :


<div id="video1"></div>
<div class="list_container">
	<a href="#video1" data-video="7WrkPR1Jovs" >Video 1</a>
	<a href="#video1" data-video="vI4LHl4yFuo" >Video 2</a>
	<a href="#video1" data-video="7WrkPR1Jovs" >Video 3</a>
	<a href="#video1" data-video="vI4LHl4yFuo" >Video 4</a>
	<a href="#video1" data-video="7WrkPR1Jovs" >Video 5</a>
</div>

JS code below :


var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var player;
function onYouTubeIframeAPIReady() {
	
  var video_id = jQuery('.list_container a').data('video');
    player = new YT.Player('video1', {
    	height: '460',
    	width: '100%',
    	videoId: video_id,
    	events: {
    		'onReady': onPlayerReady
    	}
    });
}

function onPlayerReady(event) {

  jQuery('.list_container a').click(function(){
  	var video_id = jQuery(this).data('video');
  	event.target.loadVideoById(video_id);
    });
}

Leave a Reply

Your email address will not be published. Required fields are marked *