开发者

Stop a youtube video with jquery?

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 wor开发者_如何学编程ks in all but IE, the audio keeps going in IE.

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


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

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


from the API docs:

player.stopVideo()

so in jQuery:

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


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>


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


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.


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


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.


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


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!


This works for me

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

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


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.


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


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


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>


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


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

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


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


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"


Simple like that.

include the following line in the function to close pop.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜