WebMasterCampus
WEB DEVELOPER Resources

Javascript Autoplay Youtube Video and Redirect When Video Ended

Learn using Javascript how to autoplay Youtube video and redirect when video ended


Javascript Autoplay Youtube Video and Redirect When Video Ended

If you are making a series of pages with video on different topics then it would be good idea to load your next page when youtube video finished. The following script will redirect to your desire next page when video will finished.

YouTube Player API Reference for iframe Embeds

YouTube Embedded Players and Player Parameters

Example Autoplay Youtube Video Using iFrame

<iframe id="existing-iframe-example"
          width="640" height="360"
          src="https://www.youtube.com/embed/YDnO1nUvcGg?autoplay=1&mute=1&enablejsapi=1"
          frameborder="0"
          style="border: solid 4px #37474F"
          ></iframe>

Example Autoplay Youtube Video Using API


<div id="player"></div>

<script>

var tag = document.createElement('script');
tag.src = "http://www.youtube.com/iframe_api";

var fScriptTag = document.getElementsByTagName('script')[0];
fScriptTag.parentNode.insertBefore(tag, fScriptTag);

    // Let's create youtube player
    var player;
    function onYouTubePlayerAPIReady() {
        player = new YT.Player('player', {
           //height: '768',
           //width: '1024',
           videoId: 'EJIvr6Fu7YI',
           playerVars:{'mute' : 1,'autoplay':1},
           events: {  }
        });
    }

</script>

Example Redirect Youtube Video Using API

 
<div id="player"></div>

<script>

var tag = document.createElement('script');
tag.src = "http://www.youtube.com/iframe_api";

var fScriptTag = document.getElementsByTagName('script')[0];
fScriptTag.parentNode.insertBefore(tag, fScriptTag);

    // Let's create youtube player
    var player;
    function onYouTubePlayerAPIReady() {
        player = new YT.Player('player', {
           //height: '768',
           //width: '1024',
           videoId: 'EJIvr6Fu7YI',
           playerVars:{'mute' : 1,'autoplay':1},
           events: {
            'onStateChange': onPlayerStateChange
          }
        });
    }

    // when video ends
    function onPlayerStateChange(event) {      
      if (event.data == 0)
             window.location.href = 'https://www.duckduckgo.com';
    }

</script>
Created with love and passion.