c00000fd c00000fd - 1 month ago 12
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"
src="https://www.youtube.com/embed/M7lc1UVf-VE"
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:

$("#lnkFullScreen").click(function(e)
{
e.stopPropagation();
e.preventDefault();

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

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

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


But when I run this code the
playVideo
function is
undefined
for
playerElement
.

Any idea what am I doing wrong?

PS. I want my player to remain in HTML5.

Answer

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"
        src="http://www.youtube.com/embed/M7lc1UVf-VE"
        frameborder="0" allowfullscreen>
</iframe>
<br/>
<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;

    req.call(player);
    e.preventDefault();
});

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.

Comments