RyGuy
RyGuy

Reputation: 305

Add video to page using YouTube Player API

I want to load a YouTube video on a button click using the Player API. The goal is that a user can input a video url, click a button, and then the video loads below (I excluded the form input below to make it a little simpler).

I've tried using location.reload(); to force reload the page, and checked out some other similar questions which aren't entirely helpful because they don't use the API (which I need to use for later when functionality added)

This example from the docs works fine:

<!DOCTYPE html>
<html>
<body>

<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>

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

    // 3. This function creates an <iframe> (and YouTube player)
    //    after the API code downloads.
    var player;
    function onYouTubeIframeAPIReady() {
        player = new YT.Player('player', {
            height: '390',
            width: '640',
            videoId: 'M7lc1UVf-VE',
            events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
            }
        });
    }

    // 4. The API will call this function when the video player is ready.
    function onPlayerReady(event) {
        event.target.playVideo();
    }

    // 5. The API calls this function when the player's state changes.
    //    The function indicates that when playing a video (state=1),
    //    the player should play for six seconds and then stop.
    var done = false;
    function onPlayerStateChange(event) {
        if (event.data == YT.PlayerState.PLAYING && !done) {
            setTimeout(stopVideo, 6000);
            done = true;
        }
    }
    function stopVideo() {
        player.stopVideo();
    }
</script>
</body>
</html>

I want to get something like this (very similar version) to work. I'm not sure why it doesn't currently.

<!DOCTYPE html>
<html>
<body>

<input type="submit" value="Submit" id="submit">

<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>

<script>

    document.getElementById("submit").addEventListener("click", function() {

        location.reload();

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

        // 3. This function creates an <iframe> (and YouTube player)
        //    after the API code downloads.
        var player;

        function onYouTubeIframeAPIReady() {
            player = new YT.Player('player', {
                height: '390',
                width: '640',
                videoId: 'M7lc1UVf-VE',
                events: {
                    'onReady': onPlayerReady,
                    'onStateChange': onPlayerStateChange
                }
            });
        }

        // 4. The API will call this function when the video player is ready.
        function onPlayerReady(event) {
            event.target.playVideo();
        }

        // 5. The API calls this function when the player's state changes.
        //    The function indicates that when playing a video (state=1),
        //    the player should play for six seconds and then stop.
        var done = false;

        function onPlayerStateChange(event) {
            if (event.data == YT.PlayerState.PLAYING && !done) {
                setTimeout(stopVideo, 6000);
                done = true;
            }
        }

        function stopVideo() {
            player.stopVideo();
        }

    });

</script>
</body>
</html>

Upvotes: 1

Views: 7173

Answers (1)

junvar
junvar

Reputation: 11594

You have two issues.

1) onYouTubeIframeAPIReady is never called because it is defined after the youtube API loads. You can see this by adding a console.log.

2) When you reload the page, the page reloads; i.e. your previous variables and video and everything are gone.

Here's a minimal example to load & play a youtube video on button click:

<input type="submit" value="Submit" id="submit">

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

<script src="https://www.youtube.com/iframe_api"></script>
<script>
    document.getElementById('submit').addEventListener('click', () => {
        new YT.Player('player', {
            height: '390',
            width: '640',
            videoId: 'M7lc1UVf-VE',
            events: {
                onReady: e => e.target.playVideo()
            }
        });
    });
</script>

Note, the youtube code samples are either trying to be backwards compatible or just haven't been rigorously updated. They don't follow modern styles (e.g. they use var instead of let, == instead of ===, " instead of ', etc.

Upvotes: 3

Related Questions