How to play any YouTube video dynamically using YouTube iFrame API + autoplay on mobile devices

In this blog post you will see a script that I’ve demonstrated on my YouTube channel to play any YouTube video dynamically by clicking a button or typing a video id easily.

Here is the script:

<!DOCTYPE html>
<html lang="en-us">
	<head>
		<meta charset="utf-8">
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<title>Tutorial</title>
	</head>

	<body>
		
		<!-- 1. The <iframe> (video player) will replace this <div> tag. -->
		<div id="player"></div>
		
		<button onclick="playThisVideo('ox3a3mVyfNM')">Video 1</button>
		<button onclick="playThisVideo('Xen01afIaQI')">Video 2</button>
		<button onclick="playThisVideo('n_kvlUIUH9Q')">Video 3</button>
		
		
		<input id="somevidid">
		<button onclick="playanothervideo()">Play this video</button>

		<script>
		  // 2. This code loads the IFrame Player API code asynchronously.
		  var tag = document.createElement('script');

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

		  // 3. This function creates an <iframe> (and YouTube player)
		  //    after the API code downloads.
		  
		  function onYouTubeIframeAPIReady() {
				console.log("YouTube is ready!");
		  }

		  // 4. The API will call this function when the video player is ready.
		  function onPlayerReady(event) {
			event.target.playVideo();
		  }

		  // 5. The API calls this function when the player's state changes.
		  //    The function indicates that when playing a video (state=1),
		  //    the player should play for six seconds and then stop.
		  var done = false;
		  function onPlayerStateChange(event) {
			if (event.data == YT.PlayerState.PLAYING && !done) {
			  setTimeout(stopVideo, 6000);
			  done = true;
			}
		  }
		  function stopVideo() {
			player.stopVideo();
		  }
		  
		  
		var player;
		function playThisVideo(vidid){
			if(player){
				player.destroy();
			}
			player = new YT.Player('player', {
				height: '390',
				width: '640',
				videoId: vidid,
				events: {
				'onReady': onPlayerReady,
				'onStateChange': onPlayerStateChange
				}
			});
		}
		
		
		function playanothervideo(){
			var vidid = document.getElementById("somevidid").value;
			//alert("Video: " + vidid);	
			
			playThisVideo(vidid);
		}
		  
		</script>
		
	</body>
</html>

The script is originally found here but I modified it and added a useful function to it so we can play more than one video dynamically.

Leave a Reply

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