Hide/show in JavaScript - stop playing YouTube iframe video

29,330

This is an implementation of the YouTube player API, without loading additional files. To get this work, you have to suffix all of your <iframe>'s src attribute with ?enablejsapi=1.

Example (I broke the code over a few lines for readability, you can safely omit the linebreaks):

<div id="pic3">
    <iframe width="640" height="390"
            src="http://www.youtube.com/embed/Xub4grFLbQM?enablejsapi=1"
            frameborder="0" allowfullscreen></iframe>
</div>

<div id="tS2" class="jThumbnailScroller">
.. Removed your code for readability....
    <a href="#vid3" id="link3"><img src="images/thumbs/player2.jpg" height="85"/></a>
    ....

JavaScript + jQuery code:

$(function() {
    /* elt: Optionally, a HTMLIFrameElement. This frame's video will be played,
     *       if possible. Other videos will be paused*/
    function playVideoAndPauseOthers(frame) {
        $('iframe[src*="http://www.youtube.com/embed/"]').each(function(i) {
            var func = this === frame ? 'playVideo' : 'pauseVideo';
            this.contentWindow.postMessage('{"event":"command","func":"' + func + '","args":""}', '*');
        });
    }
    $('#tS2 a[href^="#vid"]').click(function() {
        var frameId = /#vid(\d+)/.exec($(this).attr('href'));
        if (frameId !== null) {
            frameId = frameId[1]; // Get frameId
            playVideoAndPauseOthers($('#pic' + frameId + ' iframe')[0]);
        }
    });
});
Share:
29,330
Sabine Quardon
Author by

Sabine Quardon

Updated on June 06, 2020

Comments

  • Sabine Quardon
    Sabine Quardon almost 4 years

    I've used the iframe function to embed videos, and I'm hiding/showing the content and videos through JavaScript.

    I have one problem. When I press play on the first video, and then click on the next without stopping the first one, the first one just keeps on playing.

    What can I do to stop the video in the "background", when showing new content?

    $(function(){
        $("#link1").click(show1);
    });
    
    function show1(){
        $("#pic1").fadeIn();
        $("#pic2").hide();
    }
    

    I'm just using this simple JavaScript function, where the "pic1" and "pic2" id is the id of the div, the video are embedded in.

    I just can't seem to make it work. I tried to put remove, but then you can't see the video again if you want to.

    • Rob W
      Rob W over 12 years
      possible duplicate of video won't stop when div is hidden
    • Ayush
      Ayush over 12 years
    • Rob W
      Rob W over 12 years
      @xbonez Your question is not about a framed youtube video.
    • Sabine Quardon
      Sabine Quardon over 12 years
      I've tried, but i get kinda confused of the togglevideo-thing. I got about 7 videos, which will mean 7 diff id's of video, and 7 id's for a thumbnail. Wouldn't that be a lot of code? [andreasbense.dk] It's on this page, under "video".
    • Sabine Quardon
      Sabine Quardon over 12 years
      I fixed it. Added "onClick="player.stopVideo();" to all my links. and it worked - in firefox.. Not sure it's working in google chrome.
  • Sabine Quardon
    Sabine Quardon over 12 years
    You're awesome! THANK YOU :-D
  • fregante
    fregante over 10 years
    This doesn't seem to work anymore, I get this error: Blocked a frame with origin "http://www.mywebsite.com" from accessing a frame with origin "http://www.youtube.com". Protocols, domains, and ports must match. when trying to access the contentWindow property
  • Rob W
    Rob W over 10 years
    @bfred.it The method still works, or many other scripts (including the official YouTube iframe API) would break. What code are you using?
  • fregante
    fregante over 10 years
    Go here and type document.querySelectorAll('#video iframe')[0] in the console. That alone will cause that error… but document.querySelectorAll('#video iframe')[0].contentWindow.postMessage doesn't. Go figure. My bad, I suppose the function works.