Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop all YouTube iframe embeds from playing?

I'm stuck! I'm using jquery to, on click, pull a youtube json-c feed, grab the first id, and use it to prepend the html5 iframe video to the top of the ul. I then increment it and pull the second id, third id, etc and prepend them accordingly.

The problem is, when a new video is prepended, I want any of the previous videos to stop playing. Is their any way to accomplish this with javascript/jquery?

Here's the function call:

function videoCall(i) {
$.getJSON('http://gdata.youtube.com/feeds/api/standardfeeds/most_recent?v=2&max-results=50&alt=jsonc', function(vid) { 
    var fullItem ='';
    var videoID = (vid.data.items[i].id);
    var videoLink = 'http://www.youtube.com/watch?v=' + videoID;
    var videoTitle = (vid.data.items[i].title);

    fullItem += '<li class="videoItem">';
    fullItem += '<iframe title="YouTube video player" width="900" height="536" src="http://www.youtube.com/embed/' + videoID + '" frameborder="0" allowfullscreen></iframe>';
    fullItem += '<a href="mailto:?subject=ThinkerBot Video&body=' + videoLink + '">Email This</a>';
    fullItem += '</li>';

    $(fullItem).hide().prependTo('#content ul').slideDown('slow');
});
}
like image 621
RustyEight Avatar asked Mar 31 '11 17:03

RustyEight


1 Answers

You should be able to do something like this:

function players(func, args) {
    var iframes = document.getElementsByTagName('iframe');
    for (var i=0; i<iframes.length; ++i) {
        if (iframes[i]) {
            var src = iframes[i].getAttribute('src');
            if (src) {
                if (src.indexOf('youtube.com/embed') != -1) {
                    iframes[i].contentWindow.postMessage(JSON.stringify({'event': 'command','func': func,'args': args || []}), "*");
                }
            }
        }
    }
}

// example usage
players('stopVideo');
like image 52
Kim T Avatar answered Sep 21 '22 11:09

Kim T