Custom Controls for HTML5 Videos don't work - javascript

I am customising a video in html and css. So far the play button works and the full screen mode works too. But if I try to drag the slider (the one next to PLAY button) it is meant to change the position in the video too. Same with the volume button (next to MUTE button) - it doesn’t work if I try to slide it.
I wonder what is wrong with my code as I was partially following a tutorial and that’s the way they used for the tutorial.
<div id="video-container">
<!-- Video -->
<video id="video-container__video" width="640" height="365">
<source src='_assets/media/big_buck_bunny.mp4' type='video/mp4'>
</video>
<!-- Video Controls -->
<div id="video-controls">
<button type="button" id="video-controls__play-pause">Play</button>
<input type="range" id="video-controls__seek-bar" value="0">
<button type="button" id="video-controls__mute">Mute</button>
<input type="range" id="video-controls__volume-bar" min="0" max="1" step="0.1" value="1">
<button type="button" id="video-controls__full-screen">Full-Screen</button>
</div>
window.onload = function() {
//video
var video = document.getElementById("video-container__video");
//Buttons
var playButton = document.getElementById("video-controls__play-pause");
var muteButton = document.getElementById("video-controls__mute");
var fullScreenButton = document.getElementById("video-controls__full-screen");
//sliders
var seekBar = document.getElementById("video-controls__seek-bar");
var volumeBar = document.getElementById("video-controls__volume-bar");
//event listener for the play and pause button
playButton.addEventListener("click", function() {
if (video.paused == true) {
video.play();
//button text will change to Pause
playButton.innerHTML = "Pause";
} else {
//pause the video
video.pause();
//button will update its text to play
playButton.innerHTML = "Play";
}
});
// Event listener for the full-screen button
fullScreenButton.addEventListener("click", function() {
if (video.requestFullscreen) {
video.requestFullscreen();
} else if (video.mozRequestFullScreen) {
video.mozRequestFullScreen(); // Firefox
} else if (video.webkitRequestFullscreen) {
video.webkitRequestFullscreen(); // Chrome and Safari
}
});
//event listener for the change bar
seekBar.addEventListener("change", function() {
//calculate the new time
var time = video.duration * (seekBar.value / 100);
//update the video time
video.currentTime = time;
});
//the change bar will move as the video plays
video.addEventListener("timeupdate", function() {
//Calculate the slider value
var value = (100 / video.duration) * video.currentTime;
//Update the slider value
seekBar.value = value;
})
//pause the video when the slider handle is being dragged
seekBar.addEventListener("mousedown", function() {
video.pause();
});
//play the video when the
seekBar.addEventListener("mouseup", function() {
video.play();
});
volumeBar.addEventListener("change", function() {
//update the video volume
video.volume = volumeBar.value;
});
}

Related

Audio class in javascript returning undefined for duration [duplicate]

I just started to learn HTML5 and was going through HTML5 Audio player using JQuery. I coded a player with Playlist, everything works fine except the Duration with help of which my input range slider doesn't works. When I debugged I found that my duration is showing me NAN. I am setting the duration after the song is initialized.
Here is my JS code
jQuery(document).ready(function() {
container = $('.container');
playList = $('#playlist');
playListSong = $('#playlist li');
cover = $('.cover');
play = $('#play');
pause = $('#pause');
mute = $('#mute');
muted = $('#muted');
close = $('#close');
song = new Audio('music/Whistle-Flo-Rida-Mp3-Download.mp3','music/Whistle-Flo-Rida-Mp3-Download.mp3');
var canPlay = song.canPlayType('audio/mpeg;');
if (canPlay) {
song.type= 'audio/mpeg';
song.src= 'music/Whistle-Flo-Rida-Mp3-Download.mp3';
}
playListSong.click(function(){
$('#close').trigger('click');
window["song"] = new Audio('music/'+$(this).html()+'.mp3','music/'+$(this).html()+'.mp3');
$('#play').trigger('click');
});
play.live('click', function(e) {
e.preventDefault();
song.play();
//cover.attr("title", song.duration);
$(this).replaceWith('<a class="button gradient" id="pause" href="" title=""><span>k</span></a>');
$('#close').fadeIn(300);
$('#seek').attr('max',song.duration);
});
pause.live('click', function(e) {
e.preventDefault();
song.pause();
$(this).replaceWith('<a class="button gradient" id="play" href="" title=""><span>d</span></a>');
});
mute.live('click', function(e) {
e.preventDefault();
song.volume = 0;
$(this).replaceWith('<a class="button gradient" id="muted" href="" title=""><span>o</span></a>');
});
muted.live('click', function(e) {
e.preventDefault();
song.volume = 1;
$(this).replaceWith('<a class="button gradient" id="mute" href="" title=""><span>o</span></a>');
});
$('#close').click(function(e) {
e.preventDefault();
container.removeClass('containerLarge');
cover.removeClass('coverLarge');
song.pause();
song.currentTime = 0;
$('#pause').replaceWith('<a class="button gradient" id="play" href="" title=""><span>d</span></a>');
$('#close').fadeOut(300);
});
$("#seek").bind("change", function() {
song.currentTime = $(this).val();
$("#seek").attr("max", song.duration);
});
song.addEventListener('timeupdate',function (){
curtime = parseInt(song.currentTime, 10);
$("#seek").attr("value", curtime);
});
});
When I click on playlist song, the duration is always NAN but by default I have set one song, and directly on page load when I clicked Play button then the duration works fine. It never works for playlist songs.
Use the loadedmetadata event listener to get the duration for the audio as soon as the metadata is loaded. Do something like the following code:
var audio = new Audio();
audio.src = "mp3/song.mp3";
audio.addEventListener('loadedmetadata', function() {
console.log("Playing " + audio.src + ", for: " + audio.duration + "seconds.");
audio.play();
});

Video Audio still plays when the parent div is hidden

when my video's parent element is hidden is still plays the audio of the video. I need the audio to stop playing, thank you! Also if you'd like to take a look at the actual website feel free to have a look: https://accela-6b408f29a6797bfc3f-ecd2f4351342a.webflow.io/
(P.S. You will only be able to view the video screen once every 45 minutes to please block cookies for this website if you'd like to see it multiple times)
(The video can be skipped by clicking "Skip Video" then the sound continues
This is the code used to display the video:
/*Idea: add listener for hover while playing show pause*/
var bunnyVideo = document.getElementById("bVideo");
var el = document.getElementById("playButton");
//var ey = document.getElementById("pauseButton");
var replay = document.getElementById("replayButton");
//Hide replay button at start
replay.style.visibility='hidden';
pauseButton.style.visibility='hidden';
function playPause() {
replay.style.visibility='hidden';
if (bunnyVideo.paused)
{
bunnyVideo.play();
el.className = "";
}
else
{
bunnyVideo.pause();
el.className = "playButton";
}
}
function playPauseControls() {
replay.style.visibility='hidden';
if (!bunnyVideo.paused) {
el.className = "";
} else {
el.className = "playButton";
}
}
function hideHoverPauseButton(){
replay.style.visibility='hidden';
if (!bunnyVideo.paused) {
el.className = "";
} else {
el.className = "playButton";
}
}
function showHoverPauseButton(){
replay.style.visibility='hidden';
if (!bunnyVideo.paused) {
el.className = "pauseButton";
} else {
el.className = "playButton";
}
}
function videoEnd() {
replay.style.visibility='visible';
el.className = "";
bunnyVideo.setAttribute("controls","controls");
}
function showControls(){
bunnyVideo.setAttribute("controls","controls");
}
function hideControls(){
bunnyVideo.removeAttribute("controls","controls");
}
/*Google Analytics Tracker Function*/
/*Assuming you've already set up the Google Analytics script function on your webpage. This just activates a trigger event when the video plays.*/
/*function bunnyVideoView() {
ga('send', 'event', {
'eventCategory': 'Bunny Video',
'eventAction': 'play',
'eventLabel': 'Bunny Video View'
});
}*/
/* You can play with this to hide controls or not */
bunnyVideo.addEventListener("click", playPause, false);
bunnyVideo.addEventListener("play", playPauseControls, false);
bunnyVideo.addEventListener("pause", playPauseControls, false);
bunnyVideo.addEventListener("mouseover", hideControls, false);
bunnyVideo.addEventListener("mouseout", hideControls, false);
bunnyVideo.addEventListener("mouseover", showHoverPauseButton, true);
bunnyVideo.addEventListener("mouseout", hideHoverPauseButton, true);
el.addEventListener("mouseover", showHoverPauseButton, true);
el.addEventListener("mouseover", hideControls, false);
replay.addEventListener("mouseover", hideControls, false);
bunnyVideo.addEventListener("ended", videoEnd, false);
/*Google Analytics Tracker*/
/*bunnyVideo.addEventListener("play", bunnyVideoView, false);*/
<center>
<div class="video-wrapper1">
<video id="bVideo">
<source src="https://github.com/intricate-rogue/AccelaFiles/blob/master/accela-video-withsound.mp4?raw=true
" type="video/mp4" />
</video>
<div id="playButton" class="playButton" onclick="playPause()"></div>
<div id="pauseButton" class="pauseButton" onclick="playPause()"></div>
<div class="replayButton" id="replayButton" onclick="playPause()"></div>
</div>
</center>

Why is Pjax causing a load conflict with html5 video?

I'm using barba.js to create smooth page transitions with GSAP. Initially I had issues with reinitialising my jS but this is now working (debugged). However, I have an issue with html5 video - clicking on a thumbnail opens a full screen version of the video in a video modal, on a clean page load this doesn't autoplay and has custom controls which are linked to my own jS file - default controls are hidden.
For some reason when I switch pages using PJAX and the page reloads the default controls are shown, and my custom video player controls no longer control the video in question. What's weird is they still play the audio, but the video looks like it is overridden by the original file with controls enabled, I can play both videos simultaneously and hear both, but only see one video.
Basically there seems to be incompatibility between PJAX and html5 video, here is my barba.js which controls the PJAX transition (note the reinit of scripts which I have tested and which works):
barba.init({
transitions: [{
name: 'diffuse-transition',
leave(data) {
return gsap.to(data.current.container, {
opacity: 0
});
},
beforeEnter: ({ next }) => {
window.scrollTo(0, 0);
reinitScripts();
},
enter(data) {
return gsap.from(data.next.container, {
opacity: 0
});
}
}]
});
Then the html for the modal:
<div id="modalVideoWrapper">
<div id="modalVideo">
<div id="modalVideoInner">
<video id="modalVideoInteract" src="clients/moo/video/MOO_Advert_Render_v2_2.mp4" preload="auto"
poster="clients/moo/images/MOO_Video_Placeholder.jpg" class="projectFeedVideo"></video>
<div id="controls">
<div id="progressBar"><span id="progress"></span></div>
<button id="playpause" title="play" onclick="togglePlayPause()">Play</button>
</div>
<img class="close-modal" alt="Close" src="assets/icons/icon_close_modal.png" />
</div>
</div>
</div>
Then the video modal jS which works perfectly on a full page reload, just not through PJAX:
/* Set Globals */
var video = document.getElementById("modalVideoInteract");
/* End Set Globals */
/* Trigger Video Modal */
$(".pF1-Right video, #projectIntro .watchVideo").click(function () {
$("body").addClass("lock-scroll");
$("#modalVideoWrapper").fadeTo("slow", 1);
});
$(".close-modal").click(function () {
video.pause();
$('#modalVideoInteract').get(0).currentTime = 0.3;
$("#modalVideoWrapper").fadeOut("300", 0);
$("body").removeClass("lock-scroll");
});
$("#modalVideoInteract").click(function () {
$("#playpause").click();
});
/* End Trigger Video Modal */
/* Custom Controls */
video.controls = false;
function togglePlayPause() {
var playpause = document.getElementById("playpause");
if (video.paused || video.ended) {
playpause.title = "Pause Video";
playpause.innerHTML = "Pause";
video.play();
}
else {
playpause.title = "Play Video";
playpause.innerHTML = "Play";
video.pause();
}
}
function updateProgress() {
var progress = document.getElementById("progress");
var value = 0;
if (video.currentTime > 0) {
value = Math.floor((100 / video.duration) * video.currentTime);
}
progress.style.width = value + "%";
}
video.addEventListener("timeupdate", updateProgress, false);
video.addEventListener('play', function () {
var playpause = document.getElementById("playpause");
playpause.title = "Pause Video";
playpause.innerHTML = "Pause";
}, false);
video.addEventListener('pause', function () {
var playpause = document.getElementById("playpause");
playpause.title = "Play Video";
playpause.innerHTML = "Play";
}, false);
video.addEventListener('ended', function () {
this.pause();
playpause.title = "Play Again";
playpause.innerHTML = "Play Again";
}, false);
/* End Custom Controls */
What am I missing here?
Worked it out, weirdly enough several parts of the page needed to be removed so that they would reinitialise properly, so I added this to the barba transition jS:
barba.init({
transitions: [{
name: 'diffuse-transition',
leave(data) {
return gsap.to(data.current.container, {
opacity: 0
});
},
beforeEnter: ({ next }) => {
window.scrollTo(0, 0);
reinitTitleScene();
reinitScripts();
},
enter(data) {
return gsap.from(data.next.container, {
opacity: 0
});
},
afterLeave() {
reinitModal();
}
}]
});
function reinitTitleScene() {
$('#titleScene').remove();
}
function reinitModal() {
$('#modalVideoInteract').remove();
}
Hope this helps someone in need :)

Start Video When It becomes In Focus

I'm trying to figure out a way to get my video to start playing only once it becomes in focus of the viewport. The video will be in a bunch of text of an article and I would like it to only play when the user scrolls down to it
<script>
window.onload = function() {
// Video
var video = document.getElementById("video");
// Buttons
var playButton = document.getElementById("play-pause");
var playButtonImg = document.getElementById("playButtonImg");
var muteButton = document.getElementById("mute");
var muteButtonImg = document.getElementById("muteButtonImg");
// Event listener for the play/pause button
playButton.addEventListener("click", function() {
if (video.paused == true) {
// Play the video
video.play();
// Update the button text to 'Pause'
playButtonImg.src = "pause-sm.png";
} else {
// Pause the video
video.pause();
// Update the button text to 'Play'
playButtonImg.src = "play-sm.png";
}
});
video.addEventListener("ended", function(){
playButtonImg.src = "replay-sm.png";
});
// Event listener for the mute button
muteButton.addEventListener("click", function() {
if (video.muted == false) {
// Mute the video
video.muted = true;
// Update the button text
muteButtonImg.src = "mute-sm.png";
} else {
// Unmute the video
video.muted = false;
// Update the button text
muteButtonImg.src = "volume-sm.png";
}
});
// Pause the video when the seek handle is being dragged
seekBar.addEventListener("mousedown", function() {
video.pause();
});
}
</script>
If you can use jQuery, waypoints is what you seek:
http://imakewebthings.com/waypoints/

Ending a video in HTML using JavaScript events?

I am displaying a YouTube video on my html page using JavaScript.
How do I hide the video and retain the page that displayed the video using JavaScript?
I need to hide the video on a button click.
My code looks like this:
function addVideo(qId){
alert("a video");
var $videoComp = '<div class="vid" id="myytplayer"><iframe id="ifr" width="560" height="315" src="//www.youtube.com/embed/ac7KhViaVqc" allowfullscreen=""></iframe></div><div class ="main"><button class="btn btn-success" id="one" >Close video</button></div>';
$('.create-elem').append($videoComp);
$(".main").click(function(){
//$(".vid").hide();
//$("#one").hide();
function stopthevideo(){
var myPlayer = document.getElementById('myytplayer');
myPlayer.stopVideo();
}
});
This is what I do to identify end of video.
var myVideo = document.getElementById("video1");
myVideo.addEventListener('ended',onVideoEnded,false);
function onVideoEnded(e) {
if(!e) { e = window.event; }
// Make your things here
hideVideo = true;
}
Or you can always try work with https://developers.google.com/youtube/js_api_reference#Playback_status
Hope one of these will help you :)
The try to set video position at the ended event:
Save the start time and duration time to variable after loadedmetadata event.
var myVideo = document.getElementById("video1");
var videoStartTime = 0;
var videoEndTime = 0;
myVideo.addEventListener('loadedmetadata', function() {
videoStartTime = 2;
videoEndTime = 4;
this.currentTime = videoStartTime;
}, false);
If current time is greater than start time plus end of video time, pauses the video.
myVideo.addEventListener('timeupdate', function() {
if(this.currentTime > videoStartTime + videoEndTime ){
this.pause();
}
});

Categories

Resources