Conditional click events on a Youtube Video (check state if playing or stopped)

I wanted to create on click events:

  • When the video playing send user to another page
  • When the video is stopped, re-start the video

Requried javascript API:

<script src="https://www.youtube.com/iframe_api"></script>

HTML mark-up

<div class="herovideo"> <!-- this is the wrapper //-->
  <div class="herovideo-clicker"></div> <!-- this is the clicker //-->
  <div class="video-wrapper"> <!-- this is a responsive wrapper //-->
    <div id="video-placeholder"></div> <!-- this gets replaced with iframe //-->
  </div>
</div>

CSS:

<style>
	.video-wrapper {   }
	.herovideo { position:relative;  }
	.herovideo-clicker { z-index:99; position:absolute; width: 100%; height: 100%; cursor:pointer;}
	.herovideo .video-wrapper { position:relative; z-index:9; }
</style>

Javascript that will:

  • Initialise the player and define it’s appearance
  • Do the responsive resizing
  • On stae change, set the click event
<script>

var player;
function onYouTubeIframeAPIReady() {
	player = new YT.Player('video-placeholder', {
		width: 1280,
		height: 720,
		videoId: 'Write your Youtube Video ID here',
		playerVars: {
			modestbranding: 1,
			autoplay: 1,
			controls: 0,
			enablejsapi: 1,
			fs: 0,
			rel: 0,
			showinfo: 0,
			color: 'white'
		},
		events: {
			onReady: initialize,
			onStateChange: onytplayerStateChange
		}
	});
}

function initialize(){

	var $allVideos = $("iframe[src*='//player.vimeo.com'], iframe[src*='//www.youtube.com'], object, embed"),
		$fluidEl = $(".video-wrapper");

	$allVideos.each(function() {
	  $(this)
	  .attr('data-aspectRatio', this.height / this.width)
	  .removeAttr('height')
	  .removeAttr('width');
	});

	var newWidth = $fluidEl.width();
	  $allVideos.each(function() {
		var $el = $(this);
		$el
		.width(newWidth)
		.height(newWidth * $el.attr('data-aspectRatio'));
	  });

}
  
function onytplayerStateChange(newState) {

  if(newState.data == 1) {
	 // take the user to a new page while the video is playing
	 $( ".herovideo-clicker").unbind( "click" );
	 $('.herovideo-clicker').on('click', function(){
		window.location.href = 'write your URL here'; 
		return false;
	 });
  } else  {
	// restart the video if it is not playing
	$( ".herovideo-clicker").unbind( "click" );
	$('.herovideo-clicker').on('click', function(){
		player.playVideo();
		return false;
	});
  }
}

</script>

References:

  • https://github.com/chriscoyier/Fluid-Width-Video
  • https://developers.google.com/youtube/iframe_api_reference