53

I have a jquery slider that I have built, basically just three pannels that slide by applying negative left CSS values. Works great, but I have a youtube video in one slide that wont stop when I slide. I've tried display:none and Visibility:hidden which works in all but IE, the audio keeps going in IE.

Is there an easy way to kill a video with jquery?

wesbos
  • 25,839
  • 30
  • 106
  • 143

20 Answers20

98

This solution is simple, elegant and works in all browsers:

var video = $("#playerid").attr("src");
$("#playerid").attr("src","");
$("#playerid").attr("src",video);
HeyTiger
  • 981
  • 1
  • 6
  • 2
  • 9
    awesome solution, works perfectly if you don't mind reseting the video. – ehime Sep 21 '12 at 17:33
  • This worked perfectly for me. I tried the other solutions on this page but could not get any of them to work due to mismatch between http and https. – Dave Sag May 29 '14 at 07:52
  • 2
    What's amazing about this solution is that I just used it over 3 years after it was suggested, and its still the easiest one I found to implement. – joshmcode Feb 21 '15 at 21:52
  • 1
    This is by far the most elegant and easy to implement solution I found to this very same question that was plaguing. 6 hours of googling and trial and error, and then I found this gem. Only reason I could see this NOT working for folks, is if they need the video paused. – Hybrid web dev Mar 19 '15 at 06:42
  • Hey guys. I can't seem to get this one working and from what I can tell, it's because the modal code opens below where I have this code added. I have included the code just about the closing tag, but when I click on the link to activate the popup, the resulting modal code is triggering below the pasted JS code. Does anyone know why this would be? – damienoneill2001 Jun 02 '15 at 10:52
  • Still works a decade later – Sam Assoum May 11 '22 at 14:31
36

from the API docs:

player.stopVideo()

so in jQuery:

$('#playerID').get(0).stopVideo();
cobbal
  • 69,903
  • 20
  • 143
  • 156
  • Wow, that easy? What would my player ID be? – wesbos Jan 24 '10 at 20:06
  • 2
    actually, it seems to be more complicated than I first thought. It requires flash 8+ and you need to add "&enablejsapi=1" to the url. Then you have to figure out whether to call the function on the embed tag or the object tag – cobbal Jan 24 '10 at 20:20
  • I'm not able to get this to work. Why do you have to use .get(0) in this example? Also confusing is that in the example at http://code.google.com/apis/youtube/chromeless_example_1.html - the methods called on the links that control the video are Stop. So it uses "stop();" as opposed to "stopVideo();". I wasn't able to get either to work though. – Mike Eng Jan 06 '11 at 20:52
  • @Mike I'm not sure about the differences between stop and stopVideo. The `.get(0)` is to get a DOM element from the jQuery object. – cobbal Jan 06 '11 at 22:24
  • 3
    Awesom solution. To wesbos: PlayerID is not ID of youtube iframe but div around youtube iframe. For example -
    ........
    – Severe Torture Apr 13 '15 at 12:25
22

To start video

var videoURL = $('#playerID').prop('src');
videoURL += "&autoplay=1";
$('#playerID').prop('src',videoURL);

To stop video

var videoURL = $('#playerID').prop('src');
videoURL = videoURL.replace("&autoplay=1", "");
$('#playerID').prop('src','');
$('#playerID').prop('src',videoURL);

You may want to replace "&autoplay=1" with "?autoplay=1" incase there are no additional parameters

works for both vimeo and youtube on FF & Chrome

Faiz Mohamed Haneef
  • 3,418
  • 4
  • 31
  • 41
22

1.include

<script type="text/javascript" src="http://www.youtube.com/player_api"></script>

2.add your youtube iframe.

<iframe id="player" src="http://www.youtube.com/embed/YOURID?rel=0&wmode=Opaque&enablejsapi=1" frameborder="0"></iframe>

3.magic time.

      <script>
            var player;
            function onYouTubePlayerAPIReady() {player = new YT.Player('player');}
            //so on jquery event or whatever call the play or stop on the video.
            //to play player.playVideo();
            //to stop player.stopVideo();
     </script>
Kimtho6
  • 6,154
  • 9
  • 40
  • 56
Chris Wheaton
  • 251
  • 3
  • 7
  • 3
    I tried that and the element'player.stopVideo()' came back as not being defined. What am I missing? – ProfVersaggi Feb 26 '12 at 01:46
  • 1
    Do you have the script tag included and is "&enablejsapi=1" added to your iframe src? – Chris Wheaton Feb 29 '12 at 18:49
  • The most natural way to close the YouTube player seems to be using the YouTube API. Out of many published answers, this particular one does exactly this. – luqo33 Jul 12 '15 at 20:33
17

I've had this problem before and the conclusion I've come to is that the only way to stop a video in IE is to remove it from the DOM.

Felix
  • 88,392
  • 43
  • 149
  • 167
8

My solution to this that works for the modern YouTube embed format is as follows.

Assuming the iframe your video is playing in has id="#video", this simple bit of Javascript will do the job.

$(document).ready(function(){
  var stopVideo = function(player) {
    var vidSrc = player.prop('src');
    player.prop('src', ''); // to force it to pause
    player.prop('src', vidSrc);
  };

  // at some appropriate time later in your code
  stopVideo($('#video'));

});

I've seen proposed solutions to this issue involving use of the YouTube API, but if your site is not an https site, or your video is embedded using the modern format recommended by YouTube, or if you have the no-cookies option set, then those solutions don't work and you get the "TV set to a dead channel" effect instead of your video.

I've tested the above on every browser I could lay my hands on and it works very reliably.

Dave Sag
  • 13,266
  • 14
  • 86
  • 134
  • 1
    Solved my issue, thanks a ton! (was trying to simply get a youtube video to stop playing once the user moved to another "tab" in a single page app) – Kamron K. Dec 07 '14 at 12:10
8

I was facing the same problem. After a lot of alternatives what I did was just reset the embed src="" with the same URL.

Code snippet:

  $("#videocontainer").fadeOut(200);<br/>
  $("#videoplayer").attr("src",videoURL);

I was able to at least stop the video from playing when I hide it.:-)

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
JackSparrow
  • 81
  • 1
  • 1
  • Thank you! This worked for me, however I had 10 videos, and I received a js error that videoURL was not defined, so I changed videoURL to "http/fuu?args" and targetted unique id for each video iframe. Would be nice to know why videoURL didn't work. Thanks again! – Jason Mar 10 '15 at 16:38
5

if you have autoplay property in the iframe src it wont help to reload the src attr/prop so you have to replace the autoplay=1 to autoplay=0

  var stopVideo = function(player) {
    var vidSrc = player.prop('src').replace('autoplay=1','autoplay=0');
    player.prop('src', vidSrc);
  };

  stopVideo($('#video'));
talsibony
  • 8,448
  • 6
  • 47
  • 46
4

This works for me

stopIframeVideo = () => {
  let iframe = $('.video-iframe')
  iframe.each((index) => {
    iframe[index].contentWindow.postMessage('{"event":"command","func":"' + 'stopVideo' + '","args":""}', '*');
  })
};

$('.close').click(() => {
    stopIframeVideo()
});
Ann
  • 772
  • 1
  • 9
  • 17
3

Unfortunately, if id attribute of object tag don't exists, the play/stop/pauseVideo() don't work by IE.

<object style="display: block; margin-left: auto; margin-right: auto;" width="425" height="344" data="http://www.youtube.com/v/7scnebkm3r0&amp;fs=1&amp;border=1&amp;autoplay=1&amp;enablejsapi=1&amp;version=3" type="application/x-shockwave-flash"><param name="allowFullScreen" value="true" />
  <param name="allowscriptaccess" value="always" />
  <param name="allowfullscreen" value="true" />
  <param name="src" value="http://www.youtube.com/v/7scnebkm3r0&amp;fs=1&amp;border=1&amp;autoplay=1&amp;enablejsapi=1&amp;version=3" />
</object>
<object id="idexists" style="display: block; margin-left: auto; margin-right: auto;" width="425" height="344" data="http://www.youtube.com/v/pDW47HNaN84&amp;fs=1&amp;border=1&amp;autoplay=1&amp;enablejsapi=1&amp;version=3" type="application/x-shockwave-flash">
  <param name="allowscriptaccess" value="always" />
  <param name="allowFullScreen" value="true" />
  <param name="src" value="http://www.youtube.com/v/pDW47HNaN84&amp;fs=1&amp;border=1&amp;autoplay=1&amp;enablejsapi=1&amp;version=3" />
</object>
<script>
  function pauseVideo()
  {
    $("object").each
    (
      function(index)
      {
        obj = $(this).get(0);
        if (obj.pauseVideo) obj.pauseVideo();
      }
    );
  }
</script>
<button onClick="pauseVideo();">Pause</button>

Try it!

2

This works for me on both YouTube and Vimeo players. I'm basically just resetting the src attribute, so be aware that the video will go back to the beginning.

var $theSource = $theArticleDiv.find('.views-field-field-video-1 iframe').attr('src');

$theArticleDiv.find('.views-field-field-video-1 iframe').attr('src', $theSource); //reset the video so it stops playing

$theArticleDiv is my current video's container - since I have multiple videos on the page, and they're being exposed via a Drupal view at runtime, I have no idea what their ids are going to be. So I've bound muy click event to a currently visible element, found its parent, and decided that's $theArticleDiv.

('.views-field-field-video-1 iframe') finds the current video's iframe for me - in particular the one that's visible right now. That iframe has a src attribute. I just pick that up and reset it right back to what it already was, and automagically the video stops and goes back to the start. If my users want to pause and resume, they can do it without closing the video, of course - but frankly if they do close the video, I feel they can live with the fact that it's reset to the start.

HTH

Sam Moore
  • 21
  • 1
2

It took me a bit of scouting around to suss this out, but I've settled on this cross-browser implementation:

HTML

<div class="video" style="display: none">
    <div class="mask"></div>
    <a href="#" class="close-btn"><span class="fa fa-times"></span></a>
    <div class="overlay">
        <iframe id="player" width="100%" height="70%" src="//www.youtube.com/embed/Xp697DqsbUU" frameborder="0" allowfullscreen></iframe>
    </div>
</div>

jQuery

$('.launch-video').click(function() {
  $('.video').show();
  $("#player").attr('src','//www.youtube.com/embed/Xp697DqsbUU'); 
});

$('.close-btn').click(function() {
  $('.video').hide();
  $("#player").attr('src','');   
});

What it essentially does is open my lightbox and populate my src attribute, and on close, just remove the src value (then re-populates it on open).

Matt Saunders
  • 4,073
  • 7
  • 33
  • 47
2

Well, there's a much easier way of doing this. When you grab embed link for youtube video, scroll down a bit and you will see some options: iFrame Embed, Use old embed, related videos etc. There, select Use old embed link. This solves the issue.

santo101
  • 125
  • 1
  • 6
  • Just Tested in Windows XP 64bit IE8 and in Windows 7 64bit IE9. Sounds keeps playing after close/hidden div. Alos doesn't work in Snow Leopard FF 13. This works in Safari 5.1.7 & Chrome 21. I know this is an old answer, but I really wanted it to work. – Christopher Marshall Aug 20 '12 at 21:57
1

Actually you only need javascript and build the embed of the youtube video correctly with swfobject google library

This is an example

<script type="text/javascript" src="swfobject.js"></script>    
<div style="width: 425; height: 356px;">
  <div id="ytapiplayer">
    You need Flash player 8+ and JavaScript enabled to view this video.
  </div>      
  <script type="text/javascript">
    var params = { allowScriptAccess: "always" };
    var atts = { id: "myytplayer" };
    swfobject.embedSWF("http://www.youtube.com/v/y5whWXxGHUA?enablejsapi=1&playerapiid=ytplayer&version=3",
    "ytapiplayer", "425", "356", "8", null, null, params, atts);
  </script>
</div> 

After that you can call this functions:

ytplayer = document.getElementById("myytplayer");
ytplayer.playVideo();
ytplayer.pauseVideo();
ytplayer.stopVideo();
vhtellez
  • 156
  • 1
  • 8
1

I got this to work on all modern browsers, including IE9|IE8|IE7. The following code will open your YouTube video in a jQuery UI dialog modal, autoplay the video from 0:00 on dialog open, and stop video on dialog close.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.min.js" type="text/javascript"></script>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>    

<script type="text/javascript">

    google.load("swfobject", "2.1");

    function _run() {
        /* YouTube player embed for modal dialog */
        // The video to load.
        var videoID = "INSERT YOUR YOUTUBE VIDEO ID HERE"
        // Lets Flash from another domain call JavaScript
        var params = { allowScriptAccess: "always" };
        // The element id of the Flash embed
        var atts = { id: "ytPlayer" };
        // All of the magic handled by SWFObject (http://code.google.com/p/swfobject/)
        swfobject.embedSWF("http://www.youtube.com/v/" + videoID + "?version=3&enablejsapi=1&playerapiid=player1&autoplay=1",
                       "videoDiv", "879", "520", "9", null, null, params, atts);
    }
    google.setOnLoadCallback(_run);

    $(function () {
        $("#big-video").dialog({
            autoOpen: false,
            close: function (event, ui) {
                ytPlayer.stopVideo() // stops video/audio on dialog close
            },
            modal: true,
            open: function (event, ui) {
                ytPlayer.seekTo(0) // resets playback to beginning of video and then plays video
            }
        });

        $("#big-video-opener").click(function () {
            $("#big-video").dialog("open");
            return false;
        });

    });
</script>

<div id="big-video" title="Video">
    <div id="videoDiv">Loading...</div>
</div>

<a id="big-video-opener" class="button" href="#">Watch the short video</a>
dexterca
  • 11
  • 1
  • This is a little more than what the question asked for, if you know how to help with the specific problem please give a concise answer on how to do it. – zeel Nov 06 '12 at 04:29
  • can anyone show me how to make this solution work for internet explorer? – James Barracca Jun 18 '13 at 01:18
0

if you are using sometimes playerID.stopVideo(); doesnot work, here is a trick,

 function stopVideo() {
           playerID.seekTo(0);
    playerID.stopVideo();
}
0

for those who are looking javascript solution

let iframeDiv = document.getElementById('demoVideo');
                        let video = iframeDiv.src;
                        iframeDiv.src = "";
                        iframeDiv.src = video;

It perfectly worked for me just put id='demoVideo' in your iframe tag and you are good to go :)

Ajay
  • 1
  • 1
0

Add following to end of embed url

?enablejsapi=1&version=3&playerapiid=ytplayer

Eg - https://www.youtube.com/embed/wR0jg0eQsZA?enablejsapi=1&version=3&playerapiid=ytplayer"

0

YouTube Player API for iframe Embeds

Docs: https://developers.google.com/youtube/iframe_api_reference

The HTML (src with enablejsapi=1 param):

 <iframe id="existing-iframe-example"
          src="https://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1"
          ></iframe>

1 of 4 - Load iframe API

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

2 of 4 - onYouTubeIframeAPIReady function

Any web page that uses the IFrame API must also implement the following JavaScript function onYouTubeIframeAPIReady.

function onYouTubeIframeAPIReady() {
  /* execute as soon as the player API code downloads */
  console.log("Youtube API is ready);
}

3 of 4 - Create YT.Player object (Select the iframe by videoId)

/* Player */
var player;
function onYouTubeIframeAPIReady() {
  player = new YT.Player('existing-iframe-example');
}

Related: How can I use a class instead of id for new YT.Player()

4 of 4 - Use Youtube Iframe API methods:

player.stopVideo();
// player.playVideo()
// player.pauseVideo()

Click Events Part

With this in mind stop the video on any logic:

JS

/* Stop Video on click */
const stop_button = document.querySelector('[stop]');

stop_button.addEventListener("click", () => {  
  player.stopVideo();
})

jquery on()

/* Stop Video on click */
$( "[stop]" ).on( "click", function() {
  player.stopVideo();
});

Code snippet

**No way to load youtube iframe inside stackoverflow snippet (codepen demo)

/* load Youtube Iframe API */
var tag = document.createElement('script');
tag.src = 'https://www.youtube.com/iframe_api';
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
/* Player */
var player;
function onYouTubeIframeAPIReady() {
  player = new YT.Player('existing-iframe-example');
}
/* Stop Video on click */
const stop_button = document.querySelector('[stop]');

stop_button.addEventListener("click", () => {  
  player.stopVideo();
})
<button stop>Stop Video</button><br>

<iframe id="existing-iframe-example"
        width="640" height="360"
        src="https://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1"
        frameborder="0"
        style="border: solid 4px #37474F"
        ></iframe>
Ezra Siton
  • 6,887
  • 2
  • 25
  • 37
-1

Simple like that.

include the following line in the function to close pop.

$('#youriframeid').remove();
bummi
  • 27,123
  • 14
  • 62
  • 101