Stop all playing iframe videos on click a link javascript
Stopping means pausing and setting the video to time 0:
$('iframe').contents().find('video').each(function ()
{
this.currentTime = 0;
this.pause();
});
This jquery code will do exactly that.
No need to replace the src attribute and reload the video again.
Little function that I am using in my project:
function pauseAllVideos()
{
$('iframe').contents().find('video').each(function ()
{
this.pause();
});
$('video').each(function ()
{
this.pause();
});
}
Reloading all iframes just to stop them is a terrible idea. You should get advantage of what comes with HTML5.
Without using YouTube's iframe_API library; you can simply use:
var stopAllYouTubeVideos = () => {
var iframes = document.querySelectorAll('iframe');
Array.prototype.forEach.call(iframes, iframe => {
iframe.contentWindow.postMessage(JSON.stringify({ event: 'command',
func: 'stopVideo' }), '*');
});
}
stopAllYouTubeVideos();
which will stop all YouTubes iframe videos.
You can use these message keywords to start/stop/pause youtube embdded videos:
stopVideo
playVideo
pauseVideo
Check out the link below for the live demo:
https://codepen.io/mcakir/pen/JpQpwm
PS-
YouTube URL must have ?enablejsapi=1
query parameter to make this solution work.
This should stop all videos playing in all iframes on the page:
$("iframe").each(function() {
var src= $(this).attr('src');
$(this).attr('src',src);
});
Try this way,
<script language="javascript" type="text/javascript" src="jquery-1.8.2.js"></script>
<script language="javascript" type="text/javascript">
$(function(){
$('.close').click(function(){
$('iframe').attr('src', $('iframe').attr('src'));
});
});
</script>