Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop all playing iframe videos on click a link javascript

I have a list of iframe videos in my webpage.

<iframe width="520" height="360" src="http://www.youtube.com/embed/2muxrT5_a6E" frameborder="0" allowfullscreen></iframe> <iframe width="520" height="360" src="http://www.youtube.com/embed/2muxrT5_a6E" frameborder="0" allowfullscreen></iframe> <iframe width="520" height="360" src="http://www.youtube.com/embed/2muxrT5_a6E" frameborder="0" allowfullscreen></iframe> <a href="#" class="close">Stop all videos</a> 

I need to stop all playing iframe videos on click the link Stop all videos. How can i do that?

like image 508
Sam Hanson Avatar asked Nov 28 '12 05:11

Sam Hanson


2 Answers

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> 
like image 70
Swarne27 Avatar answered Sep 22 '22 22:09

Swarne27


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.

like image 26
Must Ckr Avatar answered Sep 21 '22 22:09

Must Ckr