13

I have a Youtube video embedded in a slideshow that I would like to pause when the user clicks on an img thumbnail:

<li><iframe width="430" height="241" src="http://www.youtube.com/watch?v=XjUz8IT0CYg?enablejsapi=1&theme=light&showinfo=0" frameborder="0" allowfullscreen id="my-video"></iframe></li>

I've been over the Youtube API but I'm confused how to get things started.

Does the API JS load automatically when I append ?enablejsapi to the end of the YouTube video id?

Here is my JS:

var player1 = document.getElementById('my-video');

$('img').click(function () {
  player1.pauseVideo();
})

EDIT:

Here's what I did based on Matt's answer below, for anyone wondering:

<li><iframe width="430" height="241" src="http://www.youtube.com/embed/XjUz8IT0CYg?enablejsapi=1&theme=light&showinfo=0" frameborder="0" allowfullscreen id="player-1"></iframe></li>

<li><iframe width="430" height="241" src="http://www.youtube.com/embed/HVhSasnVjMQ?enablejsapi=1&theme=light&showinfo=0" frameborder="0" allowfullscreen id="player-2"></iframe></li>

And then my JS:

var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// Create YouTube player(s) after the API code downloads.
var player1;
var player2;

function onYouTubeIframeAPIReady() {
    player1 = new YT.Player('player-1');
    player2 = new YT.Player('player-2');
}

Then in document.ready:

$(document).ready(function () {
    $(".slideshow-1 img").click(function () {
        player1.stopVideo();
    });

    $(".slideshow-2 img").click(function () {
        player2.stopVideo();
    });
}
Yahreen
  • 1,639
  • 7
  • 24
  • 38

3 Answers3

19

If you want to keep your JS in external file use:

HTML

<iframe id="player1" class="ytplayer" width="430" height="241" src="http://www.youtube.com/embed/HVhSasnVjMQ?enablejsapi=1&theme=light&showinfo=0" frameborder="0" allowfullscreen></iframe>
<iframe id="player2" class="ytplayer" width="430" height="241" src="http://www.youtube.com/embed/HVhSasnVjMQ?enablejsapi=1&theme=light&showinfo=0" frameborder="0" allowfullscreen></iframe>

JS

var yt_int, yt_players={},
    initYT = function() {
        $(".ytplayer").each(function() {
            yt_players[this.id] = new YT.Player(this.id);
        });
    };
$.getScript("//www.youtube.com/player_api", function() {
    yt_int = setInterval(function(){
        if(typeof YT === "object"){
            initYT();
            clearInterval(yt_int);
        }
    },500);
});

Control Video

yt_players['player_id'].playVideo();

The reason I do it this way is because I have the videos loading dynamically via the CMS and they open in an overlay. I set the close/open overlay functions to play/pause the video.

Roi
  • 1,597
  • 16
  • 19
  • Thank you so much for this snippet. I can't believe how hard it is to get access to that player object. This was just what I needed – Swaraj Jul 26 '13 at 23:17
  • 2
    based on your code snippet here is an http://jsfiddle.net/av359/ example thanks a lot – Pravin W Oct 20 '13 at 15:26
  • 2
    God bless you my friend! – Benn Feb 27 '14 at 20:23
  • The url to getScript needs the "https:". Stackoverflow removes it from code snippets. – J Set Mar 04 '15 at 17:34
  • @JSet it actually doesn't. That is a protocol relative url, you can read more here: http://www.paulirish.com/2010/the-protocol-relative-url/ (note: protocol relative url's require you're on a web server, it will not work on a local file) – Roi Mar 04 '15 at 21:39
  • Just thought I'd share this little extra snippet which demonstrates how you can mute the youtube video on load. ' var yt_int, yt_players={}, initYT = function() { $(".ytplayer").each(function() { yt_players[this.id] = new YT.Player(this.id, { events: { 'onReady': function(event) { event.target.mute(); } } }); }); }; ' – Abbey Mar 30 '16 at 00:16
13

Appending ?enablejsapi in the embed string does not automatically include the API code. It only registers that particular embed with the API.

You want to read the first example here: https://developers.google.com/youtube/iframe_api_reference

  1. The asynchronous code snippet downloads and executes the YT iframe API
  2. onYouTubeIframeAPIReady() is fired when the API is ready
  3. Create a new YT.Player object
  4. Your code can now call pauseVideo() on your player object

You will most likely want to disable any events on your img until onYouTubeIframeAPIReady() has been fired.

Matt Stone
  • 3,705
  • 4
  • 23
  • 40
1

I have another solution:

<iframe id="player1" class="ytplayer" width="430" height="241" src="http://www.youtube.com/embed/HVhSasnVjMQ?enablejsapi=1&theme=light&showinfo=0" frameborder="0" allowfullscreen></iframe>
<iframe id="player2" class="ytplayer" width="430" height="241" src="http://www.youtube.com/embed/HVhSasnVjMQ?enablejsapi=1&theme=light&showinfo=0" frameborder="0" allowfullscreen></iframe>

and

$('.ytplayer').each(function(){
    //this.contentWindow.postMessage('{"event":"command","func":"' + 'stopVideo' + '","args":""}', '*');
    this.contentWindow.postMessage('{"event":"command","func":"' + 'pauseVideo' + '","args":""}', '*')
});
Rijo
  • 2,568
  • 1
  • 22
  • 30