Skip to main content

YouTube Player API Reference for iframe Embeds

YouTube Player API Reference for iframe Embeds

The IFrame player API lets you embed a YouTube video player on your website and control the player using JavaScript.Using the API's JavaScript functions, you can queue videos for playback; play, pause, or stop those videos; adjust the player volume; or retrieve information about the video being played.


<script>
    // 1. 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);

    // 2. This function creates an <iframe> (and YouTube player)
    //    after the API code downloads.
    var player;
      
    function onPlayerReady(event) {
        event.target.playVideo();
    }      
    var done = false;
    function onPlayerStateChange(event) {
        if (event.data == YT.PlayerState.PLAYING && !done) {
         // setTimeout(stopVideo, 6000);
          //_gaq.push(['_trackEvent', 'Videos', 'Play', 'Sales Video']);
          ga('send', 'event', 'Videos', 'Play', 'Sales Video');
         event.target.playVideo();
         done = true;
        }
        if (event.data == YT.PlayerState.PAUSED) {
            //_gaq.push(['_trackEvent', 'Videos', 'Pause', 'Sales Video']);
            ga('send', 'event', 'Videos', 'Pause', 'Sales Video');
        }
        
        if (event.data == YT.PlayerState.ENDED) {
            //_gaq.push(['_trackEvent', 'Videos', 'Finished', 'Sales Video']);
            ga('send', 'event', 'Videos', 'Finished', 'Sales Video');
        }        
    }
    function pausedVideo() {
        //_gaq.push(['_trackEvent', 'Videos', 'Pause', 'Sales Video']);
        ga('send', 'event', 'Videos', 'Pause', 'Sales Video');
        player.stopVideo();
        $( ".video-play" ).css('display','none');
        $( ".top-head, .containt-ctr, footer, .banner-height" ).css('display','block');
        window.location.reload();    
    }
function open_video(event){
    player = new YT.Player('player', { //player is div id where you place 
          height: '100%',
          width: '100%',
          videoId: 'Z2qdLkHaW88',
          playerVars: { 
            'controls': 0,
            'showinfo': 0,
            'rel' : 0
            },
          events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
          }
    });
}
$( document ).ready(function() {    
        $('body').mouseleave(function() {
                $( ".close-this" ).css('display', 'none');
            }); 
        $('body').mouseover(function() {
            $( ".close-this" ).css('display', 'block');
        }); 
        $( ".close-this" ).on( "click", function() {
            pausedVideo();
        });
    });
<span class="video-icon" onclick="open_video();"></span>

If you want to load video automatically then change the function
    function onYouTubeIframeAPIReady() {
        player = new YT.Player('player', {
            height: '390',
            width: '640',
            videoId: 'M7lc1UVf-VE',
            playerVars: {
                color: 'white',
                playlist: 'taJ60kskkns,FG0fTKAqZ5g'
            },
            events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
            }
        });
    }

Note: 
1. player.getCurrentTime():- get the current elapsed time of a youtube video
2. Get total duration of the video with getDuration(). 
3. player.playVideo(); play video on click trigger
4. player.pauseVideo(); pause video on event trigger
5. setPlaybackQuality() : Altering the video quality
6. player.setVolume() : set the volume in percentage

function formatTime(time){
    time = Math.round(time);

    var minutes = Math.floor(time / 60),
    seconds = time - minutes * 60;

    seconds = seconds < 10 ? '0' + seconds : seconds;

    return minutes + ":" + seconds;
}
Put duration time in duration tab.
$('#duration').text(formatTime( player.getDuration() ));

Progress Bar

Create your own progress bar
$('#progress-bar').on('mouseup touchend', function (e) {

    // new time in seconds = total duration in seconds * ( value of range input / 100 )
    var newTime = player.getDuration() * (e.target.value / 100);

    // Skip video to new time.
    player.seekTo(newTime);

});

If we want the progress bar to move automatically as the video progresses. Then call the function onReady event


function updateProgressBar(){
    // Update the value of our progress bar accordingly.
    $('#progress-bar').val((player.getCurrentTime() / player.getDuration()) * 100);
}

Sound Event: 

if(player.isMuted()){
    player.unMute();
}
else{
    player.mute();
}

Playlists: 
We can play the next or previous video in a playlist.


$('#next').on('click', function () {
    player.nextVideo()
});

$('#prev').on('click', function () {
    player.previousVideo()
});
player.playVideoAt(index), used to play a specific video from the playlist.

Queue Video Dynamically

var videoId = 'h14wr4pXZFk';
player.cueVideoById(videoId);

Comments

Popular posts from this blog

A Guide to UTF-8 for PHP and MySQL

Data Encoding: A Guide to UTF-8 for PHP and MySQL As a MySQL or PHP developer, once you step beyond the comfortable confines of English-only character sets, you quickly find yourself entangled in the wonderfully wacky world of UTF-8. On a previous job, we began running into data encoding issues when displaying bios of artists from all over the world. It soon became apparent that there were problems with the stored data, as sometimes the data was correctly encoded and sometimes it was not. This led programmers to implement a hodge-podge of patches, sometimes with JavaScript, sometimes with HTML charset meta tags, sometimes with PHP, and soon. Soon, we ended up with a list of 600,000 artist bios with double- or triple encoded information, with data being stored in different ways depending on who programmed the feature or implemented the patch. A classical technical rat’s nest.Indeed, navigating through UTF-8 related data encoding issues can be a frustrating and hair-pul...

How To Create Shortcodes In WordPress

We can create own shortcode by using its predified hooks add_shortcode( 'hello-world', 'techsudhir_hello_world_shortcode' ); 1. Write the Shortcode Function Write a function with a unique name, which will execute the code you’d like the shortcode to trigger: function techsudhir_hello_world_shortcode() {    return 'Hello world!'; } Example: [hello-world] If we were to use this function normally, it would return Hello world! as a string 2. Shortcode function with parameters function techsudhir_hello_world_shortcode( $atts ) {    $a = shortcode_atts( array(       'name' => 'world'    ), $atts );    return 'Hello ' . $a['name'] . !'; } Example: [hello-world name="Sudhir"] You can also call shortcode function in PHP using do_shortcode function Example: do_shortcode('[hello-world]');

How to replace plain URLs with links

Here we will explain how to replace Urls with links from string Using PHP $string ='Rajiv Uttamchandani is an astrophysicist, human rights activist, and entrepreneur. Academy, a nonprofit organization dedicated to providing a robust technology-centered education program for refugee and displaced youth around the world.  CNN Interview - https://www.youtube.com/watch?v=EtTwGke6Jtg   CNN Interview - https://www.youtube.com/watch?v=g7pRTAppsCc&feature=youtu.be'; $string = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.%-=#]*(\?\S+)?)?)?)@', '<a href="$1">$1</a>', $string); Using Javascript <script> function linkify(inputText) {     var replacedText, replacePattern1, replacePattern2, replacePattern3;     //URLs starting with http://, https://, or ftp://     replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;     replacedText = inputT...