Hexbob6
Hexbob6

Reputation: 167

Calling a single function from the YouTube Player API?

I want to use the YouTube Player API to call a single function that will stop an embedded YT video (loaded dynamically on the page with JS and jQuery) from playing on a button click.

I'm admittedly (very) new to working with APIs for web development and despite reading through several of the other answers (such as here, here and here), I am still confused as to the necessity of the different JS components.


I have a code block that is dynamically appended multiple times to the HTML page, with the YouTube URL changing for each entry based on a separate JSON file. The added code is as follows...

<li>
  <section class="youtube-video">
    <iframe src="'theLoadedURL'?enablejsapi=1&rel=0" frameborder="0" allowfullscreen="1">
    </iframe>
  </section>
</li>

... and then I have added the <script> tag at the bottom of the <body> that loads(?) the API...

<script src="https://www.youtube.com/iframe_api"></script>

... and finally a simple button for demonstration.

<button> Stop Video </button>

I was hoping that there would be a way to then simply call the player.stopVideo(); function from the API and have it affect the already-embedded iFrame on the button click, something like...

$('button').on('click', function () {
    $('.youtube-video iframe').stopVideo();
});

... but alas, it doesn't seem to be that simple!


The documentation and other answers appear to suggest defining various variables and functions for the player, or deal with loading videos manually (rather than dynamically, as in this case); but it seems unnecessarily complex for an element that is already loaded on the page - is there something that I'm missing or an obvious way of simplifying things?

Detailed answers would be much appreciated as I'm still getting to grips with JS in general.

Thanks! :)

Upvotes: 1

Views: 1882

Answers (1)

Hexbob6
Hexbob6

Reputation: 167

So from playing around with New's fiddle from the comments, I believe I have found the simplest way of implementing the Youtube Player API, in my situation.


Firstly, it requires minor editing the HTML <li> code block that, in practice, would be loaded dynamically onto my page:

<li>
    <section class="active">
        <iframe id="youtube-video" src="https://www.youtube.com/embed/y1yFiotx3qk?
        rel=0&modestbranding=1&showinfo=0&enablejsapi=1" frameborder="0"
        allow="autoplay; encrypted-media" allowfullscreen></iframe>
    </section>
</li>

The main changes come from the addition of a class of .active being added to the <section> tag to specify the current video targeted by the YouTube Player API. The iframe then has an id of #youtube-video. It should be noted that all ids and classes are completely arbitrary.

At the bottom of the HTML's <body> I have added the API script...

<script src="https://www.youtube.com/iframe_api"></script>

... however, found that it is important that this is placed above all other <script> tags in the same location.


Following this, I have set up my JS file (with jQuery) as follows:

$(document).ready(function () {

    // Creates arbitrary global 'player' variable to be defined later
    var player;

    function onYouTubeIframeAPIReady() {

        setTimeout(function() { //Using this as seemed to come across occasional bugs in Chrome

            console.log('API Loaded!')

            // Selects first <li> tag iframe contained in a section with the class of '.active'
            var $selectedVideo = $('.active #youtube-video')[0];

            // Uses the previous variable to define the youtube player
            player = new YT.Player($selectedVideo);

        }, 100);

    }

    // Calls the Function
    onYouTubeIframeAPIReady();

});

Finally, also within the $(document).ready() function, I am able to bind the relevant YouTube Player API event handlers to the <button> HTML element:

$('button').on('click', function(){
    player.stopVideo();
});

The intention behind my code is to form part of a slideshow, and thus there should only be one section that has the .active class at any one time and this can be used to select different videos on different slides.


I've put together an example JSFiddle here that contains a better UI and more in-depth comments, which may be useful to someone in future.

Upvotes: 1

Related Questions