How to Control YouTube Video Player using JavaScript / Jquery
close
How to Control YouTube Video Player using JavaScript / Jquery

How to Control YouTube Video Player using JavaScript / Jquery

How to control YouTube video player using JavaScript

If you thinking about controlling the YouTube video player using JavaScript then this tutorial or article is for you.

Yes you can easily control YouTube video player using JavaScript and I will cover this topic in this article.

First of all we have to initialize our video player for that the code provided below is the perfect examples.
<script>
//<![CDATA[
var player;

function onYouTubeIframeAPIReady() {
    player = new YT.Player('video-placeholder', {
        width: 600,
        height: 400,
        videoId: 'Xa0Q0J5tOP0',
        playerVars: {
            color: 'white',
            playlist: 'taJ60kskkns,FG0fTKAqZ5g'
        },
        events: {
            onReady: initialize
        }
    });
}

function initialize(){

    // Update the controls on load
    updateTimerDisplay();
    updateProgressBar();

    // Clear any old interval.
    clearInterval(time_update_interval);

    // Start interval to update elapsed time display and
    // the elapsed part of the progress bar every second.
    time_update_interval = setInterval(function () {
        updateTimerDisplay();
        updateProgressBar();
    }, 1000)

}
//]]>
</script>

Xa0Q0J5tOP0 is youtube video ID.
taJ60kskkns,FG0fTKAqZ5g is youtube playlist ID's.

After the initialization of this video player now it's time to control its components separately. Now here is a list of different JavaScript functions to control different video player components.

Duration:

To See the Duration ( duration and current time ) use this function.
<span id='current-time'></span>
<span id='duration'></span>

<script>
//<![CDATA[
// This function is called by initialize()
function updateTimerDisplay(){
    // Update current time text display.
    $('#current-time').text(formatTime( player.getCurrentTime() ));
    $('#duration').text(formatTime( player.getDuration() ));
}

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;
}
//]]>
</script>


Progress Bar:

To control the progress bar of youtube video player use this code.

<input type='range' id='progress-bar'/>
<script>
//<![CDATA[
$('#progress-bar').on('mouseup touchend', function (e) {

    // Calculate the new time for the video.
    // 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);

});

// This function is called by initialize()
function updateProgressBar(){
    // Update the value of our progress bar accordingly.
    $('#progress-bar').val((player.getCurrentTime() / player.getDuration()) * 100);
}
//]]>
</script>

Play:

To control the play button use this code.
<button id='play'>Play</button>
<script>
//<![CDATA[
$('#play').on('click', function () {

    player.playVideo();

});
//]]>
</script>

Pause:

To control the pause button use this code.
<button id='pause'>Pause</button>
<script>
//<![CDATA[
$('#pause').on('click', function () {

    player.pauseVideo();

});
//]]>
</script>

Mute/Un-Mute:

To mute and un-mute video player this function will help you in any case.
<button id='mute-toggle'>Mute/Un-Mute</button>
<script>
//<![CDATA[
$('#mute-toggle').on('click', function() {
    var mute_toggle = $(this);

    if(player.isMuted()){
        player.unMute();
        mute_toggle.text('volume_up');
    }
    else{
        player.mute();
        mute_toggle.text('volume_off');
    }
});
//]]>
</script>

Control Volume:

If you want to control volume of this video player this is the code for that.
<input type='number' id='volume-input'/>
<script>
//<![CDATA[
$('#volume-input').on('change', function () {
    player.setVolume($(this).val());
});

// To get the current volume of the player use this method:
// player.getVolume()
//]]>
</script>

Speed:

To control the speed of this video player you can use the following code.
<select id="speed">
    <option>0.25</option>
    <option>0.5</option>
    <option selected="selected">1</option>
    <option>1.5</option>
    <option>2</option>
</select>
<script>
//<![CDATA[
$('#speed').on('change', function () {
    player.setPlaybackRate($(this).val());
});

// To get the current playback rate for a video use this method:
// player.getPlaybackRate()

// To get all available playback rates for the current video use:
// player.getAvailablePlaybackRates()
//]]>
</script>

Quality:

If you want to change video quality this is the code which will solve this issue for you.
<select id="quality">
    <option>small</option>
    <option>medium</option>
    <option selected="selected">large</option>
    <option>hd720</option>
    <option>hd1080</option>
    <option>highres</option>
</select>
<script>
//<![CDATA[
$('#quality').on('change', function () {
    player.setPlaybackQuality($(this).val());
});

// To get the actual video quality of the running video use this method:
// player.getPlaybackQuality()

// To get a list of the available quality formats for a video use:
// player.getAvailableQualityLevels()
//]]>
</script>

If you are playing with the youtube playlists these functions will help you alot.

Playlist Next:

This function will be used to play next video in the playlist.
<button id='next'>Playlist Next</button>
<script>
//<![CDATA[
$('#next').on('click', function () {
    player.nextVideo()
});
//]]>
</script>

Playlist Previous:

This function will be used to play previous video in the playlist.
<button id='prev'>Playlist Previous</button>
<script>
//<![CDATA[
$('#prev').on('click', function () {
    player.previousVideo()
});
//]]>
</script>

Dynamically Queue Video:

Do you look dynamic things? Wait, this function is for those who love dynamic things. This function will help you to Dynamically Queue Video.

<img class="thumbnail" src="https://image.flaticon.com/icons/svg/1042/1042339.svg" data-video-id="h14wr4pXZFk"/>
<img class="thumbnail" src="https://image.flaticon.com/icons/svg/1042/1042352.svg" data-video-id="KkFnm-7jzOA"/>
<img class="thumbnail" src="https://image.flaticon.com/icons/svg/1042/1042356.svg" data-video-id="Ph77yOQFihc"/>
<script>
//<![CDATA[
$('.thumbnail').on('click', function () {

    var url = $(this).attr('data-video-id');

    player.cueVideoById(url);

});
//]]>
</script>

These are functions that will help you in controlling youtube video player if you want.

Here i have a demo for you of this article. You can see the demo by clicking the demo button below.
View Demo

Conclusion:

Now I have made it easy for you to control the YouTube video player using JavaScript code. Now if you want you can create your own costume video player for YouTube videos.

I hope this article will help you alot and your issue will be solved.
Disqus Codes

No comments

Notifications

Disqus Logo