Stop a youtube video with jquery?

JavascriptJqueryYoutube

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

var video = $("#playerid").attr("src");
$("#playerid").attr("src","");
$("#playerid").attr("src",video);

Solution 2 - Javascript

from the API docs:

player.stopVideo()

so in jQuery:

$('#playerID').get(0).stopVideo();

Solution 3 - Javascript

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>

Solution 4 - Javascript

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

Solution 5 - Javascript

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.

Solution 6 - Javascript

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.:-)

Solution 7 - Javascript

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.

Solution 8 - Javascript

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'));

Solution 9 - Javascript

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!

Solution 10 - Javascript

This works for me

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

$('.close').click(() => {
    stopIframeVideo()
});

Solution 11 - Javascript

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.

Solution 12 - Javascript

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

Solution 13 - Javascript

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).

Solution 14 - Javascript

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>

Solution 15 - Javascript

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();

Solution 16 - Javascript

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

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

Solution 17 - Javascript

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 :)

Solution 18 - Javascript

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"

Solution 19 - Javascript

Simple like that.

include the following line in the function to close pop.

$('#youriframeid').remove();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionwesbosView Question on Stackoverflow
Solution 1 - JavascriptHeyTigerView Answer on Stackoverflow
Solution 2 - JavascriptcobbalView Answer on Stackoverflow
Solution 3 - JavascriptChris WheatonView Answer on Stackoverflow
Solution 4 - JavascriptFaiz Mohamed HaneefView Answer on Stackoverflow
Solution 5 - JavascriptFelixView Answer on Stackoverflow
Solution 6 - JavascriptJackSparrowView Answer on Stackoverflow
Solution 7 - JavascriptDave SagView Answer on Stackoverflow
Solution 8 - JavascripttalsibonyView Answer on Stackoverflow
Solution 9 - JavascriptProgz KillerView Answer on Stackoverflow
Solution 10 - JavascriptAnna LogachevaView Answer on Stackoverflow
Solution 11 - Javascriptsanto101View Answer on Stackoverflow
Solution 12 - JavascriptSam MooreView Answer on Stackoverflow
Solution 13 - JavascriptMatt SaundersView Answer on Stackoverflow
Solution 14 - JavascriptdextercaView Answer on Stackoverflow
Solution 15 - JavascriptvhtellezView Answer on Stackoverflow
Solution 16 - JavascriptDheeraj VijayView Answer on Stackoverflow
Solution 17 - JavascriptAjay View Answer on Stackoverflow
Solution 18 - JavascriptChameera W. AshanView Answer on Stackoverflow
Solution 19 - JavascriptAlex RodriguesView Answer on Stackoverflow