html5 video: play/pause custom button issue - javascript

I am using an HTML5 Video on my website, with certain other codes that basically makes usability more customized.
The video is intended to play when in view and pause when not in view. Additionally it also has a play and pause button that comes into view when the mouse hovers on the video.
At the end of the video it turns into an image because by default the html5 video would just turn to blank.
The problem is that the image turns up in the end, but the play/pause continue to appear on hover and function as play pause but only audio. You cannot see the video.
I originally wanted it to just show the picture. But would prefer to have the play pause turn into a restart button if the video ends.
I tried looking for something that would fit my existing setup, but I am not sure how to make it happen and which of these codes would I play with.
Here is a link for the site
http://minhasdistillery.com/blumersmoonshine/
<section id="feature">
<div id="trail">
<div id="videocontrol">
<a id="play-pause" class="play"><img src="images/pause.png"/></a>
</div>
<video id="video_background" preload="auto" volume="5"><!--or turn on loop="loop"-->
<source src="videos/video.webm" type="video/webm">
<source src="videos/video.mp4" type="video/mp4">
<source src="videos/video.ogv" type="video/ogg ogv">
</video>
<img id="image_background" src="images/blumer.jpg" width="100%" height="100%" />
</div><!--trail-->
</section><!--feature-->
Javascript that brings up play/pause button
<script>
window.onload = function() {
var video = document.getElementById("video_background");
var playButton = document.getElementById("play-pause");
playButton.addEventListener("click", function() {
if (video.paused == true) {
video.play();
playButton.innerHTML = "<img src='images/pause.png'/>";
} else {
video.pause();
playButton.innerHTML = "<img src='images/play.png'/>";
}
});
}
</script>
The code sets the video to play on when visible and pause otherwise
<script>
//play when video is visible
var videos = document.getElementsByTagName("video"), fraction = 0.8;
function checkScroll() {
for(var i = 0; i < videos.length; i++) {
var video = videos[i];
var x = 0,
y = 0,
w = video.offsetWidth,
h = video.offsetHeight,
r, //right
b, //bottom
visibleX, visibleY, visible,
parent;
parent = video;
while (parent && parent !== document.body) {
x += parent.offsetLeft;
y += parent.offsetTop;
parent = parent.offsetParent;
}
r = x + w;
b = y + h;
visibleX = Math.max(0, Math.min(w, window.pageXOffset + window.innerWidth - x, r - window.pageXOffset));
visibleY = Math.max(0, Math.min(h, window.pageYOffset + window.innerHeight - y, b - window.pageYOffset));
visible = visibleX * visibleY / (w * h);
if (visible > fraction) {
video.play();
} else {
video.pause();
}
}
}
window.addEventListener('scroll', checkScroll, false);
window.addEventListener('resize', checkScroll, false);
//check at least once so you don't have to wait for scrolling for the video to start
window.addEventListener('load', checkScroll, false);
checkScroll();
</script>
This one adds the photo in the end.
<script>
var video = document.getElementById('video_background');
var wrapper = document.getElementById('wrapper');
var image = document.getElementById('image_background');
video.addEventListener('ended', function() {
video.style.display = 'none';
image.style.display = 'inline';
}, false);
</script>
A JSBin of the same issue is here
JSBin For Issue
as you will see at the end of the video it will continue to show pause and play and will only play audio.
How do I get it to read that the video ended and switch the button to "replay"

Initially video display style is block and image display style is none.
Video ended event handler sets video display to none and image display to inline.
You can check video display style in button click event handler and toggle it:
playButton.addEventListener(
'click',
function(event) {
if (video.style.display === 'none') {
image.style.display = 'none';
video.style.display = 'block';
}
...
},
false
);
As an alternative add boolean flag which is intially set to false, on video ended event set it to true:
var needReplay = false;
video.addEventListener(
'ended',
function() {
...
needReplay = true;
},
false
);
playButton.addEventListener(
'click',
function(event) {
if (needReplay) {
image.style.display = 'none';
video.style.display = 'block';
needReplay = false;
}
...
},
false
);
Demo

Related

How to fade out current video and fade in new video onclick?

I want to be able to play a video when I click a button, then have a different video fade in while fading out the current video when clicking another button. This needs to be a dynamic transition with the user clicking randomly (ie, from 1 to 3 or vice versa). Here's my current code without any fading:
JS:
<script>
video = document.getElementById('video');
source = document.getElementById('source');
window.PlayVideo = function(srcVideo){
video.pause();
source.setAttribute('src', srcVideo);
video.load();
video.play();
}
</script>
HTML:
<a onclick="PlayVideo('fire.webm');"><button>Play Video 1</button></a>
<a onclick="PlayVideo('smoke.webm');"><button>Play Video 2</button></a>
<a onclick="PlayVideo('merged-rain.webm');"><button>Play Video 3</button></a>
<div id="xxxxxx">
<div>
<video id="video" width="520" height="360" loop muted controls><source id = "source"/></video>
</div>
</div>
Example link: http://nov-exl.dx.am/movie%20change.html
Any help would be appreciated, thanks.
How about something like this:
var video = document.getElementById('video');
var source = document.getElementById('source');
var timer = void 0;
window.PlayVideo = async function(srcVideo){
source.setAttribute('src', srcVideo);
fade('out');
try {
await video.pause();
await video.load();
await video.play();
fade('in');
} catch(err) {
console.log("Promise rejected");
}
}
function fade(opts){
if(typeof opacityTimer !== 'undefined') clearInterval(opacityTimer);
var opacity = opts === 'in' ? 0 : 1;
opacityTimer = setInterval(function() {
if ((opts === 'in' && opacity >= 1) ||(opts=== 'out' && opacity <=0) ){
clearInterval(timer);
}
opacity = opts === 'in' ? opacity+(opacity * 0.1 || 0.1) : opacity-(opacity * 0.1 || 0.1);
video.style.opacity = opacity;
video.style.filter = 'alpha(opacity=' + opacity * 100 + ")";
}, 25);
}

Best way to capture paused video frame to canvas

I know how to copy on frame by frame basis from a playing HTML5 video to a canvas using 2D context.
But I want to work with a paused video, change dinamically its currentTime and copy current frame of video to canvas.
My guess is some process is not called yet when video position is set with currentTime property, although the video itself does update the image it shows (but not to the canvas).
I've found that it's posible to overcome this by setting a setTimeout to do the canvas ´drawImage´ in the next step.
You can see here a jsfiddle that proves the point.
As you can see in the fiddle you can play the video, and canvas updates, but if you pause the video, mouse scroll moves currentTime of video. There, a ´seTimeout´ is needed to update the canvas, if I call the drawImage method directly, canvas doesn't update.
In short, my question is:
Is there a better way to do this? Is it posible to do this without setTimeout and inside de loop itself? Pros & Cons?
Thank you very much for reading through here!
Every time you change the currentTime of your VideoElement, a seeked Event will trigger when the video actually changed its position.
var vid = document.getElementById("v");
var canvas = document.getElementById("c");
var context = canvas.getContext('2d');
var targetFrame = document.getElementById('t');
var cw = canvas.width = 200;
var ch = canvas.height = Math.round(cw / 1.7777);
var targetOffset = 0;
window.addEventListener('wheel', function(e) {
e.preventDefault();
targetOffset = targetOffset + (e.deltaY / 1000);
targetFrame.value = targetOffset;
seek(); // for demo purpose, we only listen to wheel
return false;
});
// that's all is needed
vid.addEventListener('seeked', function() {
context.drawImage(vid, 0, 0, cw, ch);
});
// for demo
// removed the rendering loop
// now it only changes the video's currentTime property
function seek() {
targetOffset = targetOffset * 0.9;
targetFrame.value = Math.round(targetOffset * 100) / 100;
var vct = vid.currentTime - targetOffset;
if (vct < 0) {
vct = vid.duration + vct;
} else if (vct > vid.duration) {
vct = vct - vid.duration;
}
vid.currentTime = vct;
}
.column {
float: left;
width: 50%;
}
.row:after {
content: "";
display: table;
clear: both;
}
#c {
border: 1px solid black;
}
<h3>
scroll up is forward
</h3>
<div class="row">
<div class="column">
<div>
Video element:
</div>
<video controls height="120" id="v" tabindex="-1" autobuffer="auto" preload="auto">
<source type="video/webm" src="https://www.html5rocks.com/tutorials/video/basics/Chrome_ImF.webm"/>
</video>
</div>
<div class="column">
<div>
Canvas element:
</div>
<canvas id="c"></canvas>
<div>
Momentum: <input type=text id="t">
</div>
</div>
</div>

Multiple audio players but only first working

The problem is that when i have 2 or more players on html page i can only play music in the first player and the rest wont work.
my customized HTML5 audio player:
<audio id="music" preload="true">
<source src="music/interlude.mp3">
</audio>
<div id="wrapper">
<div id="audioplayer">
<button id="pButton" class="play"></button>
<div id="timeline">
<div id="playhead"></div>
</div>
</div>
</div>
and js for this:
document.addEventListener("DOMContentLoaded", function(event) {
var music = document.getElementById('music'); // id for audio element
var duration; // Duration of audio clip
var pButton = document.getElementById('pButton'); // play button
var playhead = document.getElementById('playhead'); // playhead
var timeline = document.getElementById('timeline'); // timeline
// timeline width adjusted for playhead
var timelineWidth = timeline.offsetWidth - playhead.offsetWidth;
// play button event listenter
pButton.addEventListener("click", play);
// timeupdate event listener
music.addEventListener("timeupdate", timeUpdate, false);
// makes timeline clickable
timeline.addEventListener("click", function(event) {
moveplayhead(event);
music.currentTime = duration * clickPercent(event);
}, false);
// returns click as decimal (.77) of the total timelineWidth
function clickPercent(event) {
return (event.clientX - getPosition(timeline)) / timelineWidth;
}
// makes playhead draggable
playhead.addEventListener('mousedown', mouseDown, false);
window.addEventListener('mouseup', mouseUp, false);
// Boolean value so that audio position is updated only when the playhead is released
var onplayhead = false;
// mouseDown EventListener
function mouseDown() {
onplayhead = true;
window.addEventListener('mousemove', moveplayhead, true);
music.removeEventListener('timeupdate', timeUpdate, false);
}
// mouseUp EventListener
// getting input from all mouse clicks
function mouseUp(event) {
if (onplayhead == true) {
moveplayhead(event);
window.removeEventListener('mousemove', moveplayhead, true);
// change current time
music.currentTime = duration * clickPercent(event);
music.addEventListener('timeupdate', timeUpdate, false);
}
onplayhead = false;
}
// mousemove EventListener
// Moves playhead as user drags
function moveplayhead(event) {
var newMargLeft = event.clientX - getPosition(timeline);
if (newMargLeft >= 0 && newMargLeft <= timelineWidth) {
playhead.style.marginLeft = newMargLeft + "px";
}
if (newMargLeft < 0) {
playhead.style.marginLeft = "0px";
}
if (newMargLeft > timelineWidth) {
playhead.style.marginLeft = timelineWidth + "px";
}
}
// timeUpdate
// Synchronizes playhead position with current point in audio
function timeUpdate() {
var playPercent = timelineWidth * (music.currentTime / duration);
playhead.style.marginLeft = playPercent + "px";
if (music.currentTime == duration) {
pButton.className = "";
pButton.className = "play";
}
}
//Play and Pause
function play() {
// start music
if (music.paused) {
music.play();
// remove play, add pause
pButton.className = "";
pButton.className = "pause";
} else { // pause music
music.pause();
// remove pause, add play
pButton.className = "";
pButton.className = "play";
}
}
// Gets audio file duration
music.addEventListener("canplaythrough", function() {
duration = music.duration;
}, false);
// getPosition
// Returns elements left position relative to top-left of viewport
function getPosition(el) {
return el.getBoundingClientRect().left;
}
/* DOMContentLoaded*/
});
i belive the problem is somewhere in the js code but i cant figure out where.
i took the code form here
I notice that you're using a lot of IDs. When the "first of something" works on a page, usually it's IDs that are causing the issue.
Change all of your IDs for your <audio> players to class attributes. You will also need to update your JavaScript as well, from something like this:
var music = document.getElementById('music');
music.addEventListener(...
To something more like this:
var music = document.querySelectorAll(".music"); // class="music"
for (var i = 0; i < music.length; i++) {
music[i].addEventListener(...
You should find that this will work for you.

How to make HTML5 video fade in when it has finished loading?

I'm trying to have my HTML5 video element fade in when it loads, (I'm currently having it appear using Javascript canplaythrough as you can see in the code you see below, but it's a little harsh.) How can I get the HTML5 video element to fade in gently? I'm OK with JavaScript or jquery, but I don't know either one very well, so some complete code would be very helpful!
Here's the code: (if you run the code with the Run Code Snippet, it doesn't work well, so I highly suggest to go to my website, it's on is my video page here and works if you wait a 30 seconds/minute (until the video loads): jeffarries.com/videos.
<script>
var e = document.getElementById("myVideo");
e.style.display = 'none'
var vid = document.getElementById("myVideo");
vid.oncanplaythrough = function() {
var e = document.getElementById("myVideo");
e.style.display = 'block'
};
</script>
<video style="display: block;" id="myVideo" width="320" height="176" controls>
<source src="http://www.jeffarries.com/videos/jeff_arries_productions_intro.mp4" type="video/mp4">
Your browser does not support HTML5 video.
</video>
Thanks for you time and effort!
Here's how to fade in the video with javascript
var e = document.getElementById("myVideo");
e.style.opacity = 0;
var vid = document.getElementById("myVideo");
vid.oncanplaythrough = function() {
setTimeout(function() {
var e = document.getElementById('myVideo');
fade(e);
}, 5000);
};
function fade(element) {
var op = 0;
var timer = setInterval(function() {
if (op >= 1) clearInterval(timer);
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op += op * 0.1 || 0.1;
}, 50);
}
FIDDLE

Auto Full Screen Toggle When Video Plays HTML5

I am having video clip which is due to play in Timer when Timer gets tick after few minutes.
What I want is whenever the video starts playing it should automatically go into FullScreen mode and when it stops it, however comes back to position because as soon as Video stops I have Timer Ticked.
I know this requestFullScreen() method but I don't know how to call it when video starts playing?
Any Help will be appreciated!!
Regards and Thanks!
var video = document.createElement('video');
video.src = 'urlToVideo.ogg';
video.style.width = window.innerWidth;
video.style.height = window.innerHeight;
video.autoPlay = true;
document.getElementById('video2').appendChild(video);
Are you looking for something like this?
video = document.getElementById('video');
function onTick(){
video.play();
}
video.onPlay = function() {
if (video.requestFullscreen) {
video.requestFullscreen();
} else if (video.msRequestFullscreen) {
video.msRequestFullscreen();
} else if (video.mozRequestFullScreen) {
video.mozRequestFullScreen();
} else if (video.webkitRequestFullscreen) {
video.webkitRequestFullscreen();
}
};
video.onended = function(e) {
if(video.exitFullscreen) {
video.exitFullscreen();
} else if(video.mozCancelFullScreen) {
video.mozCancelFullScreen();
} else if(video.webkitExitFullscreen) {
video.webkitExitFullscreen();
}
};
Do something like this :
<script>
window.onload = function(){
var el = document.getElementById("OnTick");
el.addEventListener("click", function(){
el.style.display = 'none';
var videoContener = document.getElementById('video2');
var video = document.createElement('video');
videoContener.style.width = window.innerWidth;
videoContener.style.height = window.innerHeight;
video.src = 'http://techslides.com/demos/sample-videos/small.ogv';
video.style.width = "100%";
video.autoPlay = true;
video.controls = true;
videoContener.appendChild(video);
}, false);
}
</script>
<body style='margin:0px'>
<div id='video2' style='overflow: hidden;'></div>
<span id='OnTick' style='width:20px;height:20px;background-color:#323232;display:block'> </span>
</body>
autoplay doesn't work

Categories