admin管理员组文章数量:1134247
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?
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?
Share Improve this question asked Jan 24, 2010 at 19:55 wesboswesbos 26.3k31 gold badges108 silver badges144 bronze badges 3- i am not using any api..just the iframe ...how can i stop it? – HIRA THAKUR Commented Sep 27, 2013 at 13:39
- checkout my solution on below link stackoverflow.com/a/32822713/1716053 – Anand Deep Singh Commented Sep 28, 2015 at 12:16
- this simple solution still works: stackoverflow.com/questions/14136566/… – M3RS Commented Mar 9, 2018 at 17:14
20 Answers
Reset to default 98This 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'));
This works for me
stopIframeVideo = () => {
let iframe = $('.video-iframe')
iframe.each((index) => {
iframe[index].contentWindow.postMessage('{"event":"command","func":"' + 'stopVideo' + '","args":""}', '*');
})
};
$('.close').click(() => {
stopIframeVideo()
});
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&fs=1&border=1&autoplay=1&enablejsapi=1&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&fs=1&border=1&autoplay=1&enablejsapi=1&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&fs=1&border=1&autoplay=1&enablejsapi=1&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&fs=1&border=1&autoplay=1&enablejsapi=1&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!
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"
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>
Simple like that.
include the following line in the function to close pop.
$('#youriframeid').remove();
本文标签: javascriptStop a youtube video with jqueryStack Overflow
版权声明:本文标题:javascript - Stop a youtube video with jquery? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736808292a1953786.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论