play/pause video onclick firefox - javascript

I want videos to play/pause when you click on them. Firefox has this behaviour by default. Chrome does not. The simple solution I came up with was setting a click event with jQuery.
var video = $('#myVideo');
var videoDomObj = video.get(0);
//click event for the video itself
video.on('click', function(e){
//when video is clicked it should be paused when playing and vise versa
if (videoDomObj.paused){
videoDomObj.play();
} else{
videoDomObj.pause();
}
});
jsfiddle
This will work in IE and Chrome. However, this will result in a conflict in Firefox, since it will instantly call the default event afterwards and will not play the video at all. e.preventDefault() fixes this problem, but will break all the other controls in Firefox. While they still work, they will play/pause the video. Is there an easy solution for this?

In fact the raw code worked like a charm:
document.getElementById('myVideo').onclick = function(e) {
e.preventDefault();
if (this.paused){
this.play();
} else{
this.pause();
}
}
The jQuery equivalent should be:
jQuery('#myVideo').on('click', function(e) {
e.preventDefault();
if (this.paused){
this.play();
} else{
this.pause();
}
});
But as you said that breaks the video controlls, desired and simplest solution for this could be selecting a parent element (or adding a container, if required):
var video = document.getElementById('myVideo');
video.parentElement.onclick = function(e) {
if (video.paused){
video.play();
} else{
video.pause();
}
}
jQuery:
var $video = jQuery('#myVideo'), video = $video.get(0);
$video.parent().on('click', function(e) {
if (video.paused){
video.play();
} else{
video.pause();
}
});

The only solution I found was to detect the browser for this special case, since the problem only occurs in firefox and it has this feature by default anyway.
jsfiddle
//jQuery video element
var video = $('#myVideo');
//DOM element for HTML5 media events
var videoDomObj = video.get(0);
//detect if firefox
var is_firefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
//only bind click event if not firefox to prevent broken controls - firefox pauses/plays videos on click by default anyway
if (!is_firefox){
video.on('click', function(e){
//when video is clicked it should be paused when playing and vise versa
if (videoDomObj.paused){
videoDomObj.play();
} else{
videoDomObj.pause();
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<video id="myVideo" width="100%" controls>
<source src="http://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
Your browser does not support HTML5 video.
</video>

Related

JS play button for HTML5 does not work on iOS mobile

I'm trying to get an HTML5 video to play on mobile iOS. Desktop & android work fine.
Clicking the button enters fullscreen mode and plays the video.
I'm seeing reports that some cannot click the button at all though the video thumbnail is loading. The breakdown is currently:
iOS 16.0.2 not working
iOS 15.2.1 works using safari but not firefox or chrome
HTML snippet
`
<div class="video-player">
<video loop="true" width="400px" preload="auto" playsinline="true" controls="true">
<source src="media/video.mp4" type="video/mp4" />
<source src="media/video.webm" type="video/webm" />
<p>Your browser doesn't support HTML5 video. Here is
a link to the video instead </p>
</video>
<button><img src="img/play_video.svg"></button>
</div>
Script in Use
/* Get elements */
var brimmingVideo = document.querySelector('#brimming .video-player video');
var brimmingFullscreen = document.querySelector('#brimming .video-player button');
var brimmingIcon = document.querySelector('#brimming .video-player button img');
/* Build out functions */
// toggle play/pause
function brimmingtogglePlay() {
var method = brimmingVideo.paused ? 'play' : 'pause';
brimmingVideo[method]();
}
// Create fullscreen video button
function brimmingtoggleFullscreen() {
if (brimmingVideo.requestFullScreen) {
brimmingVideo.requestFullScreen();
brimmingtogglePlay();
} else if (brimmingVideo.webkitRequestFullScreen) {
brimmingVideo.webkitRequestFullScreen();
brimmingtogglePlay();
} else if (brimmingVideo.mozRequestFullScreen) {
brimmingVideo.mozRequestFullScreen();
brimmingtogglePlay();
} else if (vid.webkitEnterFullscreen) {
vid.webkitEnterFullscreen();
}
;
brimmingVideo.controls = true;
brimmingVideo.muted = false;
brimmingIcon.className = "hide";
}
// what happens when you exit fullscreen
function brimmingexitHandler() {
if (document.webkitIsFullScreen === false) {
brimmingtogglePlay();
brimmingVideo.muted = true;
brimmingVideo.controls = false;
} else if (document.mozFullScreen === false) {
brimmingtogglePlay();
brimmingVideo.muted = true;
brimmingVideo.controls = false;
} else if (document.msFullscreenElement === false) {
brimmingtogglePlay();
brimmingVideo.muted = true;
brimmingVideo.controls = false;
}
}
/* Hook up event listeners */
// Click events
brimmingFullscreen.addEventListener('click', brimmingtoggleFullscreen);
// Exit fullscreen event
brimmingVideo.addEventListener('fullscreenchange', brimmingexitHandler, false);
brimmingVideo.addEventListener('mozfullscreenchange', brimmingexitHandler, false);
brimmingVideo.addEventListener('MSFullscreenChange', brimmingexitHandler, false);
brimmingVideo.addEventListener('webkitfullscreenchange', brimmingexitHandler, false);
`
Three things are causing this problem:
At javascript, removing return false; of the event listener.
At the stylesheet, the element which calls the action must have the property cursor: pointer;. Probably Apple put this requirement in these calls for best feedback on a user interface.
Again at the stylesheet, we can't set display: none; for hidden input because some browsers don't accept clicks on elements that aren't displayed. (This doesn't apply for you)
Also, the general rule is to "grab" DOM elements only after DOM was loaded!

unable to pause video via jquery in mobile

Below is code i am using to play and pause video, it works fine in my desktop
when we click vidoe it opens and plays in fullscreen when press again vidoe should get paused with alert messaged pause .
when i play it in my andorid browser unable to get alert message
link :http://liveweave.com/miaQVr
Js code:
/* Write JavaScript here */
$(document).ready(function() {
var v = document.getElementById("myVideo");
$('#myVideo').on('click', v, function (e) {
if (v.paused === false) {
v.pause();
alert("pause");
} else {
v.webkitEnterFullscreen();
v.play();
}
return false;
});
});
html code:
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<video width="80%" height="auto" controls="controls" id="myVideo">
<source src="http://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4" />
</video>
Isn't it a problem with touch even handling? Maybe you should consider adding touch support to your script? Like that:
$('#myVideo').on('touchstart click', ...
You should then remember to stop propagation (remove ghost clicking) with:
e.stopPropagation();
In future you can also check if you're in mobile or not with:
if(e.type == "touchstart") {
// Handle touchstart event.
} else if(e.type == "click") {
// Handle click event.
}
http://jsfiddle.net/Lhzyggqn/
You can also check if you're in mobile in this way:
var clickHandler = ('ontouchstart' in document.documentElement ? "touchstart" : "click");
http://jsfiddle.net/hcwwLrhq/

Show poster image or pause button when HTML5 video is paused?

Hi I'm coding a local site for an iPad and have a video without controls that plays and pauses when clicked on. Is it possible to show the poster image when the video is paused? Or show a pause button in the center? Here's the code I have for playing and pausing:
<script type='text/javascript'>//<![CDATA[
window.onload=function(){
var overlay = document.getElementById('video-overlay');
var video = document.getElementById('video');
var videoPlaying = false;
overlay.onclick = function() {
if (videoPlaying) {
video.pause();
videoPlaying = false;
}
else {
video.play();
videoPlaying = true;
}
}
}//]]>
</script>
and the HTML for the video
<div id='video-overlay'></div>
<video width="768" height="432" poster="thumbnail2.jpg" id='video'>
<source src="PhantomFuse3_TechVideo_h264.mp4" type="video/mp4">
</video>
Another solution is to call:
video.load()
It will redisplay the poster image. it will restart the video on next interaction, but you can save the time stamp and start playing from there if you wish.
You will have to register pause event on the video.
Something like this:
JSFiddle code
Of course you should modify this for your needs and add some structure. Haven't tried it on iPad though. Also to note: registering click will introduce 300ms lag on tap event. You should look at touchstart event for touch devices and register both click and touchstart.
var overlay = document.getElementById('video-overlay'),
video = document.getElementById('video'),
videoPlaying = false;
function hideOverlay() {
overlay.style.display = "none";
videoPlaying = true;
video.play();
}
function showOverlay() {
// this check is to differentiate seek and actual pause
if (video.readyState === 4) {
overlay.style.display = "block";
videoPlaying = true;
}
}
video.addEventListener('pause', showOverlay);
overlay.addEventListener('click', hideOverlay);

How to combine exisiting full screen mode and video pause?

I somehow managed to put two options in one button: when clicking, the video starts to play and enters full screen at the same time.
This is the html:
<video id="video1" class="video-small">
<source src="video/Marinela+Pinguinos-HD.mp4" type="video/mp4" class="video-file">
<source src="video/Marinela_Pinguinos-HD.webm" type="video/webm" class="video-file">
</video>
<button id="play" class="full-play-button" onclick="vidplay(); goFullscreen('video1')">Play fullscreen</button>
JAVASCRIPT:
function vidplay() {
var video = document.getElementById("video1");
var button = document.getElementsByClassName("full-play-button");
if (video.paused) {
video.play();
button.textContent = "||";
} else {
video.pause();
button.textContent = ">";
}
}
function goFullscreen(id) {
// Get the element that we want to take into fullscreen mode
var element = document.getElementById(id);
// These function will not exist in the browsers that don't support fullscreen mode yet,
// so we'll have to check to see if they're available before calling them.
if (element.mozRequestFullScreen) {
// This is how to go into fullscren mode in Firefox
// Note the "moz" prefix, which is short for Mozilla.
element.mozRequestFullScreen();
} else if (element.webkitRequestFullScreen) {
// This is how to go into fullscreen mode in Chrome and Safari
// Both of those browsers are based on the Webkit project, hence the same prefix.
element.webkitRequestFullScreen();
}
}
So far things go smooth. When entering full screen, there's a default player-like thing at the bottom, with a button offering the possibility to exit full screen.
What I would like to achieve is to be able to pause the video when clicking that button, but I have no idea how.
What I can think of is some kind of a function that detects if we're full screen or not, and if we're not, it would pause/stop (not sure which I prefer yet) the video.
This is what came to my mind, but I'm really a newbie in JS and it doesn't work:
function exitPause() {
var video = document.getElementById("video1");
if (document.exitFullscreen) {
video.pause();
}
else if (document.mozCancelFullScreen) {
video.pause();
}
else if (document.webkitExitFullscreen) {
video.pause();
}
else if (element.msExitFullscreen) {
video.pause();
}
}
What am I doing wrong? How can I make it happen?
Use fullscreenchange event handler:
video.addEventListener(
'fullscreenchange',
function(event) {
if (!document.fullscreenElement) {
video.pause();
}
},
false
);
Note: care for vendor prefixes.
Thanks to Igor Gilyazov I managed to go a bit further. This is how the code looks now:
function vidplay() {
var video = document.getElementById("video1");
var button = document.getElementsByClassName("full-play-button");
video.addEventListener(
'webkitfullscreenchange',
function(event) {
if (!document.fullscreenElement && video.paused) {
video.play();
}
else {
video.pause();
}
},
false
);
}
and going full screen:
function goFullscreen(id) {
// Get the element that we want to take into fullscreen mode
var element = document.getElementById(id);
// These function will not exist in the browsers that don't support fullscreen mode yet,
// so we'll have to check to see if they're available before calling them.
if (element.mozRequestFullScreen) {
// This is how to go into fullscren mode in Firefox
// Note the "moz" prefix, which is short for Mozilla.
element.mozRequestFullScreen();
} else if (element.webkitRequestFullScreen) {
// This is how to go into fullscreen mode in Chrome and Safari
// Both of those browsers are based on the Webkit project, hence the same prefix.
element.webkitRequestFullScreen();
}
// Hooray, now we're in fullscreen mode!
}
What happens now is when I first click the button, it goes full screen and the video plays. When going back to small screen, it pauses.
This is great.
Unfortunately it happens only every second time (the next time it keeps being paused no matter if going full or small, then right again, then wrong and so on).
I know I'm close, but it's not fully working yet, any ideas for modifications?

Detect if HTML5 Video element is playing [duplicate]

This question already has answers here:
How to tell if a <video> element is currently playing?
(7 answers)
Closed 1 year ago.
I've looked through a couple of questions to find out if an HTML5 element is playing, but can't find the answer. I've looked at the W3 documentation and it has an event named "playing" but I can't seem to get it to work.
This is my current code:
var stream = document.getElementsByTagName('video');
function pauseStream() {
if (stream.playing) {
for (var i = 0; i < stream.length; i++) {
stream[i].pause();
$("body > header").addClass("paused_note");
$(".paused_note").text("Stream Paused");
$('.paused_note').css("opacity", "1");
}
}
}
It seems to me like you could just check for !stream.paused.
Check my answer at How to tell if a <video> element is currently playing?: MediaElement does not have a property that tells if it is playing or not. But you could define a custom property for it.
Object.defineProperty(HTMLMediaElement.prototype, 'playing', {
get: function(){
return !!(this.currentTime > 0 && !this.paused && !this.ended && this.readyState > 2);
}
})
Now you can use it on video or audio elements like this:
if(document.querySelector('video').playing){
// Do anything you want to
}
Note : This answer was given in 2011. Please check the updated documentation on HTML5 video before proceeding.
If you just want to know whether the video is paused, use the flag stream.paused.
There is no property for a video element in getting its playing status. But there is one event "playing" which will be triggered when it starts to play. An Event called "ended" is also triggered when it stops playing.
So the solution is:
Declare one variable videoStatus.
Add event handlers for different events of video.
Update videoStatus using the event handlers.
Use videoStatus to identify the status of the video.
This page will give you a better idea about video events. Play the video on this page and see how the events are triggered.
http://www.w3.org/2010/05/video/mediaevents.html
jQuery(document).on('click', 'video', function(){
if (this.paused) {
this.play();
} else {
this.pause();
}
});
Add eventlisteners to your media element. Possible events that can be triggered are: Audio and video media events
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Html5 media events</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body >
<div id="output"></div>
<video id="myVideo" width="320" height="176" controls autoplay>
<source src="http://www.w3schools.com/tags/mov_bbb.mp4" type="video/mp4">
<source src="http://www.w3schools.com/tags/mov_bbb.ogg" type="video/ogg">
</video>
<script>
var media = document.getElementById('myVideo');
// Playing event
media.addEventListener("playing", function() {
$("#output").html("Playing event triggered");
});
// Pause event
media.addEventListener("pause", function() {
$("#output").html("Pause event triggered");
});
// Seeking event
media.addEventListener("seeking", function() {
$("#output").html("Seeking event triggered");
});
// Volume changed event
media.addEventListener("volumechange", function(e) {
$("#output").html("Volumechange event triggered");
});
</script>
</body>
</html>
Best approach:
function playPauseThisVideo(this_video_id) {
var this_video = document.getElementById(this_video_id);
if (this_video.paused) {
console.log("VIDEO IS PAUSED");
} else {
console.log("VIDEO IS PLAYING");
}
}
I encountered a similar problem where I was not able to add event listeners to the player until after it had already started playing, so #Diode's method unfortunately would not work. My solution was check if the player's "paused" property was set to true or not. This works because "paused" is set to true even before the video ever starts playing and after it ends, not just when a user has clicked "pause".
You can use 'playing' event listener =>
const video = document.querySelector('#myVideo');
video.addEventListener("playing", function () {
// Write Your Code
});
Here is what we are using at http://www.develop.com/webcasts to keep people from accidentally leaving the page while a video is playing or paused.
$(document).ready(function() {
var video = $("video#webcast_video");
if (video.length <= 0) {
return;
}
window.onbeforeunload = function () {
var htmlVideo = video[0];
if (htmlVideo.currentTime < 0.01 || htmlVideo.ended) {
return null;
}
return "Leaving this page will stop your video.";
};
}
a bit example
var audio = new Audio('https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3')
if (audio.paused) {
audio.play()
} else {
audio.pause()
}
I just looked at the link #tracevipin added (http://www.w3.org/2010/05/video/mediaevents.html), and I saw a property named "paused".
I have ust tested it and it works just fine.
This is my code - by calling the function play() the video plays or pauses and the button image is changed.
By calling the function volume() the volume is turned on/off and the button image also changes.
function play() {
var video = document.getElementById('slidevideo');
if (video.paused) {
video.play()
play_img.src = 'img/pause.png';
}
else {
video.pause()
play_img.src = 'img/play.png';
}
}
function volume() {
var video = document.getElementById('slidevideo');
var img = document.getElementById('volume_img');
if (video.volume > 0) {
video.volume = 0
volume_img.src = 'img/volume_off.png';
}
else {
video.volume = 1
volume_img.src = 'img/volume_on.png';
}
}
I just did it very simply using onpause and onplay properties of the html video tag. Create some javascript function to toggle a global variable so that the page knows the status of the video for other functions.
Javascript below:
// onPause function
function videoPause() {
videoPlaying = 0;
}
// onPause function
function videoPlay() {
videoPlaying = 1;
}
Html video tag:
<video id="mainVideo" width="660" controls onplay="videoPlay();" onpause="videoPause();" >
<source src="video/myvideo.mp4" type="video/mp4">
</video>
than you can use onclick javascript to do something depending on the status variable in this case videoPlaying.
hope this helps...
My requirement was to click on the video and pause if it was playing or play if it was paused. This worked for me.
<video id="myVideo" #elem width="320" height="176" autoplay (click)="playIfPaused(elem)">
<source src="your source" type="video/mp4">
</video>
inside app.component.ts
playIfPaused(file){
file.paused ? file.play(): file.pause();
}
var video_switch = 0;
function play() {
var media = document.getElementById('video');
if (video_switch == 0)
{
media.play();
video_switch = 1;
}
else if (video_switch == 1)
{
media.pause();
video_switch = 0;
}
}
I just added that to the media object manually
let media = document.querySelector('.my-video');
media.isplaying = false;
...
if(media.isplaying) //do something
Then just toggle it when i hit play or pause.
a bit example when playing video
let v = document.getElementById('video-plan');
v.onplay = function() {
console.log('Start video')
};

Categories