c00000fd c00000fd - 3 months ago 24
Javascript Question

How to add a button to play YouTube video full screen using JavaScript?

I'm coding a Google Chrome extension where I embed a YouTube video:

<iframe id="ytplayer" type="text/html" width="640" height="360"
frameborder="0" allowfullscreen>

I then added a button below that should allow a user to click to play this video in full screen:

<a href="#" id="lnkFullScreen">Play full screen</a>

The work is done via JavaScript (and jQuery) using the code I found here:


var playerElement = document.getElementById("ytplayer");

playerElement.playVideo(); //`playVideo` is undefined

var requestFullScreen = playerElement.requestFullScreen || playerElement.mozRequestFullScreen || playerElement.webkitRequestFullScreen;
if (requestFullScreen)

But when I run this code the
function is

Any idea what am I doing wrong?

PS. I want my player to remain in HTML5.


There is a little trick to do this without the Youtube API. You can add the PHP variable &autoplay=1 to the src attribute of your <iframe>. Before adding it, check if the scr attribute has already other variables attached, and, if so, add it using & instead of ?. Then open the player in fullscreen, and you're done.

Your HTML structure will be something like:

<iframe id="player" type="text/html" width="640" height="360"
        frameborder="0" allowfullscreen>
<a href="#" id="play-fullscreen">Play full screen</a>

And here is the code you need:

var fullscreen = document.getElementById('play-fullscreen'),
    player = document.getElementById('player');

fullscreen.addEventListener('click', function (e) {
    if (~player.src.indexOf('?')) player.src += '&autoplay=1';
    else player.src += '?autoplay=1';

    var req = player.requestFullscreen
        || player.webkitRequestFullscreen
        || player.mozRequestFullScreen
        || player.msRequestFullscreen;


Unfortunately I can't provide you a working example, because Stack Overflow and tools like JSFiddle, CodePen etc don't allow frames running in their code snippets.