I'm using YouTube iframe to embed videos on my site.
<iframe width="100%" height="443" class="yvideo" id="p1QgNF6J1h0"
src="http://www.youtube.com/embed/p1QgNF6J1h0?rel=0&controls=0&hd=1&showinfo=0&enablejsapi=1"
frameborder="0" allowfullscreen>
</iframe>
And i have multiplie videos on the same page.
I want to stop all of them or one of them in a click of a button using javascript or so.
Is it possible?
UPDATE:
I tried what Talvi Watia said and used:
$('#myStopClickButton').click(function(){
$('.yvideo').each(function(){
$(this).stopVideo();
});
});
I'm getting:
Uncaught TypeError: Object [object Object] has no method 'stopVideo'
Unfortunately these API's evolve very fast. As of May 2015, the proposed solutions don't work anymore, as the player object has no stopVideo method.
A reliable solution is to be found in this page (1) and it works with an:
<iframe id="youtube_player" class="yt_player_iframe" width="640" height="360" src="http://www.youtube.com/embed/aHUBlv5_K8Y?enablejsapi=1&version=3&playerapiid=ytplayer" allowfullscreen="true" allowscriptaccess="always" frameborder="0"></iframe>
and the following JS/jQuery code:
$('.yt_player_iframe').each(function(){
this.contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*')
});
If anyone is still looking for the answer, i've solved it like so:
$("#photos").on("hide",function(){
var leg=$('.videoPlayer').attr("src");
$('.videoPlayer').attr("src",leg);
});
Where #photos is the ID of the modal and .videoPlayer is the class of the iframe.
Basically it refreshes the src attribute (and stops playing the video).
So,
$('#myStopClickButton').click(function(){
$('.yvideo').each(function(){
var el_src = $(this).attr("src");
$(this).attr("src",el_src);
});
});
should do the trick.
Here is a codepen, it worked for me.
I was searching for the simplest solution for embedding the YT video within an iframe, and I feel this is it.
What I needed was to have the video appear in a modal window and stop playing when it was closed
Here is the code : (from: https://codepen.io/anon/pen/GBjqQr)
<div>Play Video</div>
<div>Stop Video</div>
<div>Pause Video</div>
<iframe class="youtube-video" width="560" height="315" src="https://www.youtube.com/embed/glEiPXAYE-U?enablejsapi=1&version=3&playerapiid=ytplayer" frameborder="0" allowfullscreen></iframe>
$('a.play-video').click(function(){
$('.youtube-video')[0].contentWindow.postMessage('{"event":"command","func":"' + 'playVideo' + '","args":""}', '*');
});
$('a.stop-video').click(function(){
$('.youtube-video')[0].contentWindow.postMessage('{"event":"command","func":"' + 'stopVideo' + '","args":""}', '*');
});
$('a.pause-video').click(function(){
$('.youtube-video')[0].contentWindow.postMessage('{"event":"command","func":"' + 'pauseVideo' + '","args":""}', '*');
});
Additionally, if you want it to autoplay in a DOM-object that is not yet visible, such as a modal window, if I used the same button to play the video that I was using to show the modal it would not work so I used THIS:
https://www.youtube.com/embed/EzAGZCPSOfg?autoplay=1&enablejsapi=1&version=3&playerapiid=ytplayer
Note: The ?autoplay=1& where it's placed and the use of the '&' before the next property to allow the pause to continue to work.
You may want to review through the Youtube JavaScript API Reference docs.
When you embed your video(s) on the page, you will need to pass this parameter:
http://www.youtube.com/v/VIDEO_ID?version=3&enablejsapi=1
If you want a stop all videos button, you can setup a javascript routine to loop through your videos and stop them:
player.stopVideo()
This does involve keeping track of all the page IDs for each video on the page. Even simpler might be to make a class and then use jQuery.each.
$('#myStopClickButton').click(function(){
$('.myVideoClass').each(function(){
$(this).stopVideo();
});
});
APIs are messy because they keep changing. This pure javascript way worked for me:
<div id="divScope" class="boom-lightbox" style="display: none;">
<iframe id="ytplayer" width="720" height="405" src="https://www.youtube.com/embed/M7lc1UVf-VE" frameborder="0" allowfullscreen> </iframe>
</div>
//if I want i can set scope to a specific region
var myScope = document.getElementById('divScope');
//otherwise set scope as the entire document
//var myScope = document;
//if there is an iframe inside maybe embedded multimedia video/audio, we should reload so it stops playing
var iframes = myScope.getElementsByTagName("iframe");
if (iframes != null) {
for (var i = 0; i < iframes.length; i++) {
iframes[i].src = iframes[i].src; //causes a reload so it stops playing, music, video, etc.
}
}
Talvi's answer may still work, but that Youtube Javascript API has been marked as deprecated. You should now be using the newer Youtube IFrame API.
The documentation provides a few ways to accomplish video embedding, but for your goal, you'd include the following:
//load 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);
//will be youtube player references once API is loaded
var players = [];
//gets called once the player API has loaded
function onYouTubeIframeAPIReady() {
$('.myiframeclass').each(function() {
var frame = $(this);
//create each instance using the individual iframe id
var player = new YT.Player(frame.attr('id'));
players.push(player);
});
}
//global stop button click handler
$('#mybutton').click(function(){
//loop through each Youtube player instance and call stopVideo()
for (var i in players) {
var player = players[i];
player.stopVideo();
}
});
One cannot simply overestimate this post and answers thx OP and helpers.
My solution with just video_id exchanging:
<div style="pointer-events: none;">
<iframe id="myVideo" src="https://www.youtube.com/embed/video_id?rel=0&modestbranding=1&fs=0&controls=0&autoplay=1&showinfo=0&version=3&enablejsapi=1" width="560" height="315" frameborder="0"></iframe> </div>
<button id="play">PLAY</button>
<button id="pause">PAUSE</button>
<script>
$('#play').click(function() {
$('#myVideo').each(function(){
var frame = document.getElementById("myVideo");
frame.contentWindow.postMessage(
'{"event":"command","func":"playVideo","args":""}',
'*');
});
});
$('#pause').click(function() {
$('#myVideo').each(function(){
var frame = document.getElementById("myVideo");
frame.contentWindow.postMessage(
'{"event":"command","func":"pauseVideo","args":""}',
'*');
});
});
</script>
Easiest ways is
var frame = document.getElementById("iframeid");
frame.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
For a Twitter Bootstrap modal/popup with a video inside, this worked for me:
$('.modal.stop-video-on-close').on('hidden.bs.modal', function(e) {
$('.video-to-stop', this).each(function() {
this.contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<div id="vid" class="modal stop-video-on-close"
tabindex="-1" role="dialog" aria-labelledby="Title">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Title</h4>
</div>
<div class="modal-body">
<iframe class="video-to-stop center-block"
src="https://www.youtube.com/embed/3q4LzDPK6ps?enablejsapi=1&rel=0"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
frameborder="0" allowfullscreen>
</iframe>
</div>
<div class="modal-footer">
<button class="btn btn-danger waves-effect waves-light"
data-dismiss="modal" type="button">Close</button>
</div>
</div>
</div>
</div>
<button class="btn btn-success" data-toggle="modal"
data-target="#vid" type="button">Open video modal</button>
Based on Marco's answer, notice that I just needed to add the enablejsapi=1 parameter to the video URL (rel=0 is just for not displaying related videos at the end). The JS postMessage function is what does all the heavy lifting, it actually stops the video.
The snippet may not display the video due to request permissions, but in a regular browser this should work as of November of 2018.
This is the most straightforward solution that I have found.
Very important! Add ?enablejsapi=1 parameter to the iframe src attribute. E.g. scr="https://youtube.com/embed/VIDEO_ID?enablejsapi=1
var iframe = document.querySelector('iframe'); or however you want to get a hold of the element.
iframe.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
Essentially, this code is getting a hold of the Youtube Player object which is contained within the <iframe> element. See HTMLIFrameElement.contentWindow on MDN and postMessage(). Finally, Google provides a Javascript API reference here for all available functions.
Here's a pure javascript solution,
<iframe
width="100%"
height="443"
class="yvideo"
id="p1QgNF6J1h0"
src="http://www.youtube.com/embed/p1QgNF6J1h0?rel=0&controls=0&hd=1&showinfo=0&enablejsapi=1"
frameborder="0"
allowfullscreen>
</iframe>
<button id="myStopClickButton">Stop</button>
<script>
document.getElementById("myStopClickButton").addEventListener("click", function(evt){
var video = document.getElementsByClassName("yvideo");
for (var i=0; i<video.length; i++) {
video.item(i).contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*');
}
});
How we Pause/stop YouTube iframe to when we use embed videos in modalpopup
$('#close_one').click(function (e) {
let link = document.querySelector('.divclass');// get iframe class
let link = document.querySelector('#divid');// get iframe id
let video_src = link.getAttribute('src');
$('.youtube-video').children('iframe').attr('src', ''); // set iframe parent div value null
$('.youtube-video').children('iframe').attr('src', video_src);// set iframe src again it works perfect
});
see also How to pause or stop an iframe youtube video when you leave a tab view or minimise your Ionic App
$scope.stopVideo = function() {
var iframe = document.getElementsByTagName("iframe")[0].contentWindow;
iframe.postMessage('{"event":"command","func":"'+'stopVideo'+ '","args":""}', '*');
}
$('#aboutVideo .close').on('click',function(){
var reSrc = $('.aboutPlayer').attr("src");
$('.aboutPlayer').attr("src",reSrc)
})
#aboutVideo{
width: 100%;
height: 100%;
}
#aboutVideo .modal-dialog, #aboutVideo .modal-dialog .modal-content, #aboutVideo .modal-dialog .modal-content .modal-body{
width: 100%;
height: 100%;
margin: 0 !important;
padding: 0 !important;
}
#aboutVideo .modal-header{
padding: 0px;
border-bottom: 0px solid #e5e5e5;
position: absolute;
right: 4%;
top: 4%;
}
#aboutVideo .modal-header .close{
opacity: 1;
position: absolute;
z-index: 99;
color: #fff;
}
#aboutVideo .modal-header button.close{
border-radius: 50%;
width: 7vw;
height: 7vw;
position: absolute;
right: 4%;
top: 7%;
background: aliceblue;
}
#aboutVideo .modal-header button.close:hover{
background-color: rgba(255, 255, 255, 0.28);
}
#aboutVideo .modal-header button.close img{
width: 20px;
margin-top: -0.2vw;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<li class="see-video fa" type="button" data-toggle="modal" data-target="#aboutVideo">
<label>SEE VIDEO</label>
</li>
<div class="modal fade" id="aboutVideo" tabindex="-1" role="dialog" aria-labelledby="aboutVideoLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true"><img src="http://www.freeiconspng.com/uploads/white-close-button-png-16.png"></span></button>
</div>
<div class="modal-body">
<iframe class="aboutPlayer" width="100%" height="100%" src="https://www.youtube.com/embed/fju9ii8YsGs?autoplay=0&showinfo=0&controls=2&rel=0" frameborder="0" allowfullscreen poster="https://www.google.co.in/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&cad=rja&uact=8&ved=0ahUKEwiOvaagmqfWAhUHMY8KHUuJCnkQjRwIBw&url=http%3A%2F%2Fnodeframework.com%2F&psig=AFQjCNEaHveDtZ81veNPSvQDx4IqaE_Tzw&ust=1505565378467268"></iframe>
</div>
</div>
</div>
</div>
here is my solution using updated youtube API. Includes start, stop, pause.
https://codesandbox.io/s/youtube-video-player-73x4b
var vid_element = $('.youtube-player');
vid_element.detach();
$('#parent').append(vid_element);
I find detaching and then appending the element more reliable than re-assigning the src attribute.
There is a very easy way to achieve
if you are in JS
function pauseVideo(){
document.getElementById("myVideoId").contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*');
}
<!DOCTYPE html>
<html>
<body>
<iframe id="myVideoId" src="https://www.youtube.com/embed/Q63qjIXMqwU?enablejsapi=1"></iframe>
<button onclick = {pauseVideo()}>Pause</button>
</body>
</html>
if you are using react js
export const VideoPlayer = () =>{
const videoooo = useRef();
const pauseVideo = () => {
//at the place of pauseVideo you can use "stopVideo", "playVideo"
videoooo.current.contentWindow.postMessage(
'{"event":"command","func":"pauseVideo","args":""}',
"*"
);
};
return(<> <iframe
ref={videoooo}
id="myVideoId"
src="https://www.youtube.com/embed/Q63qjIXMqwU?enablejsapi=1"
></iframe>
<button
onClick={() => {
pauseVideo();
}}
>
Pause
</button></>)
}
Solution for React with TypeScript
interface props {
videoId: string;
}
function YoutubeEmbedded (props:Props) {
const { videoId } = props;
const pauseVideo = () => {
// At the place of pauseVideo you can use "stopVideo", "playVideo"
var iframe = document.querySelector("iframe");
iframe?.contentWindow?.postMessage(
'{"event":"command","func":"stopVideo","args":""}',
"*"
);
};
const handleCloseBtnClick = () => {
pauseVideo();
setShowVideoModal(false);
};
return(
<iframe
src={`https://www.youtube-nocookie.com/embed/${videoId}?enablejsapi=1`}
title="YouTube video player"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowFullScreen={true}
frameBorder={0}
/>
<button
onClick={handleCloseBtnClick}
/>
)}
There is a blank image (blank.png) with background hover effect, which works. I click on the image and it hides, then the video div shows, which works. What I can't figure out is how to get the video to play on the click on original blank image.
I have it working most of the way, but can't get the video to play on click of the image.
I am not the best with scripting.
An example of what I have done:
http://jsfiddle.net/3s8EC/2/
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('.custom-th').click(function() {
$('.custom-th').fadeOut('fast', function() {
$("#thevideo").css("display","block");
});
});
});
</script>
<style>
#imageID {background: url(http://edigi.co/Video-Intro.jpg) no-repeat;
height: 370px;
width: 100%;
}
#imageID:hover {
background: url(http://edigi.co/Video-Intro-Hover.jpg) no-repeat;
}
</style>
<div style="width: 100%; height: 370px; background-color: #000;">
<div id="promovid">
<div class="custom-th">
<img src="http://edigi.co/blank.png" id="imageID" width="100%" height="370" />
</div>
<div id="thevideo" style="display:none; padding: 0px;">
<center>
<video onclick="this.play();" preload="auto" width="600" height="370">
<source src="http://edigi.co/Impatto_Branding_Agency-Large.mp4" type="video/mp4"/>
</video>
</center>
</div>
</div>
</div>
Any help is appreciated, but since I am not the best with scripting an actual example, or edit the jsfiddle, would be totally super awesome.
Thanks in advance for the help.
Just add a $("video").click();
Like this:
$(document).ready(function() {
$('.custom-th').click(function() {
$('.custom-th').fadeOut('fast', function() {
$("#thevideo").css("display","block");
$("video").click();
});
});
});
Add an id to the video if you have multiple videos on the page and use it's id instead of "video" in the selector.
I'm making an interactive world map gif, using javascript and html5, here is my code so far:
<!DOCTYPE html>
<html>
<head>
<title>World Map</title>
<body>
<p>Click on a clickable area of the map for more info.</p>
<img src ="worldmap.gif" width="576" height="307" alt="World Map" usemap="#worldmap">
<map name="worldmap">
<area shape="rect" coords="265,49,279,64" href="
but now I'm stuck, firstly i want to know how to link to a video within the html5 video tags, upon the clicking of the linked coordinates, and also how to set javascript parameters within this, such as swapping videos etc. I have the code to be able to do the swap with the videos once the link is clicked, and I have the code to do the coordinates, I just don't know how to put it together.
Thanks so much for you help, but want to keep it super simple using the method i've done and kind of understand (if it works) here is my super simple code
<!DOCTYPE html>
<html>
<head>
<title>World Map</title>
<body>
<p>Click on a clickable area of the map for more info.</p>
<img src ="worldmap.gif" width="576" height="307" alt="World Map" usemap="#worldmap">
<map name="worldmap">
<area shape="rect" coords="265,49,279,64" <video src="ukanthem.mp4"></video>
</map>
</body>
</head>
</html>
the map opens on the page, but the clickable area does not appear to be there?
UPDATE:
So the coordinates still don't work, there is no area to click
also the video's appear on the same page as my map, I would like them on a seperate page, any help? also the video's aren't recognised, it says "video cannot be found, may have been removed from the server. http 404"
World Map
Click on a clickable area of the map for more info.
<map name="worldmap">
<area shape="rect" coords="265,49,279,64" onclick="playVideo()">
<video id="video1" class="true" autoplay controls width="420">
<source src="ukanthem.mp4" type="video/mp4">
<source src="ukanthem.mp4" type="video/ogg">
</video>
<video id="video2" class=flase" width="420" controls>
<source src="beef.mp4">
</video>
<button id="hideButton" onclick="swap();">Switch</button>
<script>
var flag=true;
function swap() {
var myVideo1=document.getElementById("Video1");
var myVideo2=document.getElementById("video2");
flag=!flag;
video1.setAttribute("class", flag);
video2.setAttribute("class", !flag);
if (flag) {
video2.pause();
video1.play();
} else {
video1.pause();
video2.play();
}
}
</script>
</map>
</body>
</head>
</html>
Look at my code again please :)
Ok super simple.
You can put an Onclick action to your area tag.
Like this.
<area .... onclick="playVideo()">
And for your HTML 5 video tag...
<video id="video1" width="420">
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video>
And a Javascript to do things for you:
This part is for the normal HEAD HTML tag <-------
<script>
function playVideo() {
var myVideo=document.getElementById("video1");
myVideo.play();
}
</script>
If you want it super easy this is super easy, and i havent used any jquery, or new stuff. Let me know how it goes :)
You need a video tag:
<video src="urlofvideo"></video>
You can use jQuery to bind the click events on the image map:
jQuery(document).ready(function($) {
$('area').bind('click', function(event) {
event.preventDefault();
//url of video
var url = this.href;
//Here your code to start the video
...
});
});
Im not 100% sure i understood your question, but i made you this. Its a map with cords on, this is without the old map method, but its with HTML, CSS and Jquery instead.
Sorry if i totally misunderstood, but its my shoot :)
<style type="text/css">
.map_image { display: block; width: 1280px; height: 960px; background-repeat: no-repeat; }
.map_image .map_link { display: block; position: absolute; text-indent: -999em; overflow: hidden; }
.map_image #paris { width: 150px; height: 80px; top: 11px; left: 11px; border: 1px solid red; }
.map_image #copenhagen { width: 150px; height: 80px; top: 40px; left: 177px; border: 1px solid yellow;}
</style>
<div class="map_image" style="background-image: url('your_picture.jpg');">
<a class="map_link" id="paris" title="google.com"></a>
<a class="map_link" id="copenhagen" title=""></a>
</div>
<script>
$("#paris").click(function() {
// play a video about paris
alert("paris");
});
$("#copenhagen").click(function() {
// play a video about paris
alert("copenhagen");
});
</script>