html5 video can't play after pause - javascript

I am struggling with the auto pause and then play(manual) again issue.The video is pausing after 2 seconds which is fine. Now there is another button and on click that button the video should start playing from the position it was paused.
Here is my code(html):
<div class="restart">Restart after pause</div>
<video id="video" width="400" height="400" id="video" src="http://media.w3.org/2010/05/sintel/trailer.mp4" controls autoplay />
jquery:
jQuery(document).ready(function ($) {
$('#video').get(0).play();
setInterval(function () {
if ($('#video').get(0).currentTime >= 2) {
$('#video').get(0).pause();
}
}, 100);
$(".restart").click(function(event){
$('#video').get(0).play();
setInterval(function () {
if ($('#video').get(0).currentTime >= 6) {
$('#video').get(0).pause();
}
}, 100);
});
});
I am definitely not on the right path regarding current time and set time.Please suggest.
The JSFiddle is
http://jsfiddle.net/squidraj/KmQxL/10/
Thanks in advance.

Please review this fiddle: http://jsfiddle.net/VZuuF/1/
I got rid of your setIntervals as they are unneccessary with the timeupdate event available.
$(document).ready(function()
{
var checkedFirst = false;
var checkedSecond = false;
$player = $('#video').get(0);
$player.play();
$player.addEventListener('timeupdate', function(event)
{
console.log($player.currentTime);
if ($player.currentTime >= 2 && !checkedFirst)
{
checkedFirst = true;
$player.pause();
}
if ($player.currentTime >= 6 && !checkedSecond)
{
checkedSecond = true;
$player.pause();
}
});
$(".restart").click(function(event)
{
$player.play();
});
});

Related

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 :)

Implementing Autoplay on glider.js

So I'm working with glider.js (https://nickpiscitelli.github.io/Glider.js/) on my website for handling slides, because I really want to keep it minimal (I know there are other sliders out there, but glider.js is the lightest). However, I really need the autoplay function, but I can't seem to be able to make it work (I don't really know my way around JS, I just copy code snippets for things I need)
I found some code for an autoplay, it looks like this:
function sliderAuto(slider, miliseconds) {
slider.isLastSlide = function() {
return slider.page >= slider.dots.childElementCount - 1;
}
var slide = function() {
slider.slideTimeout = setTimeout(function() {
function slideTo() {
return slider.isLastSlide() ? 0 : slider.page + 1;
}
slider.scrollItem(slideTo(), true);
}, miliseconds);
}
slider.ele.addEventListener('glider-animated', function(event) {
window.clearInterval(slider.slideTimeout);
slide();
});
slide();
}
But I don't know how to activate it, to make it work. I know I should pass the parameters to "slider" and "miliseconds", but I don't know what exactly should I pass, should I set a special class to each slide, and pass that class? Let's say my html is the following:
<div class="glider-contain">
<div class="glider">
<div>your content here</div>
<div>your content here</div>
<div>your content here</div>
<div>your content here</div>
</div>
How do I make the autoplay work? Thanks!
Based on the docs that you've linked and the code snippet i would say that
First things first, slider parameter is supposed to be your glidder object (what you created with new Glidder(..., and milliseconds is the amount of time in milliseconds that each slide will be visible.
Now, an example of what it could look like:
<div class="glider-contain">
<div id="glider" class="glider">
<div class="placeholder">1</div>
<div class="placeholder">2</div>
<div class="placeholder">3</div>
<div class="placeholder">4</div>
</div>
</div>
const glider = new Glider(document.getElementById('glider'));
function sliderAuto(slider, miliseconds) {
const slidesCount = slider.track.childElementCount;
let slideTimeout = null;
let nextIndex = 1;
function slide () {
slideTimeout = setTimeout(
function () {
if (nextIndex >= slidesCount ) {
nextIndex = 0;
}
slider.scrollItem(nextIndex++);
},
miliseconds
);
}
slider.ele.addEventListener('glider-animated', function() {
window.clearInterval(slideTimeout);
slide();
});
slide();
}
sliderAuto(glider, 1000)
I've edited the snippet a bit because you don't seem to use dots.
working fiddle
I have tweaked the accepted answer to pause autoplay on mouse hover. In addition, you can handle autoplay loop with the repeat argument of the slideAutoPaly function.
var slider = new Glider(document.querySelector('.glider'), {
slidesToScroll: 1,
slidesToShow: 1,
dots: '#dots',
arrows: {
prev: '.glider-prev',
next: '.glider-next'
}
});
slideAutoPaly(slider, '.glider');
function slideAutoPaly(glider, selector, delay = 5000, repeat = true) {
let autoplay = null;
const slidesCount = glider.track.childElementCount;
let nextIndex = 1;
let pause = true;
function slide() {
autoplay = setInterval(() => {
if (nextIndex >= slidesCount) {
if (!repeat) {
clearInterval(autoplay);
} else {
nextIndex = 0;
}
}
glider.scrollItem(nextIndex++);
}, delay);
}
slide();
var element = document.querySelector(selector);
element.addEventListener('mouseover', (event) => {
if (pause) {
clearInterval(autoplay);
pause = false;
}
}, 300);
element.addEventListener('mouseout', (event) => {
if (!pause) {
slide();
pause = true;
}
}, 300);
}
Also, check the Github issue: https://github.com/NickPiscitelli/Glider.js/issues/43

How to loop a video 3 times only?

I want to loop a video three times only. Rendering it in a for loop doesn't seem to work properly.
I am wondering how to do this with an HTML video.
I have this HTML video.
<div id="video" class="Adform-video"></div>
And this JS
(function() {
Floating.setup({
clicktag: dhtml.getVar('clickTAG', 'http://example.com'),
target: dhtml.getVar('landingPageTarget', '_blank'),
video: {
sources: dhtml.getVar('videoSources'),
poster: dhtml.getAsset(3),
clicktag: dhtml.getVar('clickTAG')
}
});
Floating.init();
})();
var Floating = (function() {
var videoPlayer;
var banner = dhtml.byId('banner'),
closeButton = dhtml.byId('closeButton'),
video = dhtml.byId('video'),
clickArea = dhtml.byId('click-area'),
lib = Adform.RMB.lib;
function setup(settings) {
for (var prop in settings) {
if (_settings[prop] instanceof Object) {
for (var prop2 in settings[prop]) {
_settings[prop][prop2] = settings[prop][prop2];
}
} else {
_settings[prop] = settings[prop];
}
}
}
var _settings = {
clicktag: null,
target: null,
video: null
};
function init() {
createVideoPlayer();
}
closeButton.onclick = function (event) {
dhtml.external.close && dhtml.external.close();
};
clickArea.onclick = function() {
stopVideo();
window.open(_settings.clicktag, _settings.target);
};
function createVideoPlayer() {
var videoSettings = _settings.video;
videoPlayer = Adform.Component.VideoPlayer.create({
sources: videoSettings.sources,
clicktag: videoSettings.clicktag,
loop: videoSettings.loop,
muted: videoSettings.muted,
poster: videoSettings.poster,
theme: 'v2'
});
if (videoPlayer) {
videoPlayer.removeClass('adform-video-container');
videoPlayer.addClass('video-container');
videoPlayer.appendTo(video);
}
function landPoster() {
if(!lib.isWinPhone) {
videoPlayer.video.stop();
}
}
videoPlayer.poster.node().onclick = landPoster;
if (lib.isAndroid && lib.isFF) {
lib.addEvent(video, 'click', function(){}, false);
}
}
function stopVideo() {
if (videoPlayer.video.state === 'playing') videoPlayer.video.pause();
}
return {
setup: setup,
init: init
};
})();
The video will be used as an ad, and therefore I will only loop through it trice.
I have looked at these posts but they didn't seem to work:
Loop HTML5 video
Prop video loop
How can I do that?
Check out the standard HTML5 video element's onended event handler. Set up a simple JS event function with a integer counter and use the pause feature of video element when counter reaches 3. This link should help!
https://www.w3schools.com/TAGS/av_event_ended.asp
Also, I'm curious to know why exactly you want a video to loop only thrice...
Anyway, if the functionality is somewhat similar to a small animation(of a small video) which should be played 3 times, consider making a GIF animation with three hard-coded repetitions!
PROBLEM SOLVED
<!DOCTYPE html>
<html>
<body>
<video id="myVideo" width="320" height="176" autoplay controls>
<source src="mov_bbb.mp4" type="video/mp4">
<source src="mov_bbb.ogg" type="video/ogg">
Your browser does not support the audio element.
</video>
<script>
var aud = document.getElementById("myVideo");
var a=0;
aud.onended = function() {
a=a+1;
if(a!=3)
{
aud.play();
}
};
</script>
</body>
</html>

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();
}
});

HTML5 video addEventListener 'ended' not fired

I have made a video slider that cycles trough video's. I tested the code several time when I was working on it, but a week later when I set the content online it did not function anymore.
What the problem is:
Firefox > Works fine, the addEventListener gets called and all is well
Chrome > Works fine, no errors but the addEventListener is not called and the cycle is not continued.
Is this a common Chrome bug, or did I bug my own code?
The cycle that I have created is this>
/* SLIDER */
var counter = 0;
var vid_count = 2;
var logotime = 2000;
var waittime = 5000;
function mainRotation(index){
loadVideo(index);
}
function loadVideo(index){
var video = document.getElementById('slideVideo' + index);
if(video.getAttribute("src")==null) {
video.setAttribute("src", './templates/tacticalghillies/video/slidevideo_' + index + '.mp4');
video.load();
}
else{
video.currentTime = 0;
$('#slideVideo' + index).show();
}
$('#slideImage').addClass('fadeout');
var timing = setInterval(function(){
showVideo(index, function(){
if(counter < vid_count-1){
counter++;
mainRotation(counter);
}
else{
mainRotation(counter);
counter = 0;
}
});
clearInterval(timing);
}, waittime)
}
function showVideo(index, cb){
//fade in video opacity
//play video
//video ended:
var video = document.getElementById('slideVideo' + index);
video.play();
console.log("playing");
video.addEventListener('ended', myHandler, false);
function myHandler(e){
if(!e) { e = window.event; }
console.log("eddd");
$('#slideImage').removeClass('fadeout');
var timer = setInterval(function() {
clearInterval(timer);
$('#slideVideo' + index).hide();
cb();
}, logotime);
}
}
Just to be clear this is the HTML that corrosponds with this piece of code:
<div class="animation">
<img class="a_aligned" id="slideImage" src="./images/slide_holder.png">
<video class="a_aligned slideVideo" width="1280" style="max-width:1280px;" id="slideVideo0" ></video>
<video class="a_aligned slideVideo" width="1280" style="max-width:1280px;" id="slideVideo1" ></video>
<img class="a_aligned" style="z-index:-1;" src="./images/slide_overlay.png">
</div>
Exactly same problem here... Didn't find yet how to solve this situation.
For information, this exactly same code was working well yesterday. It happend when I updated Chrome to the version 38.0.2125.104
Actually my exact code is :
$(videoBack).on("ended", function(){ [...]
Edit: Because I had a demo to do, I have use a quick fix, but I still have to figure why Chrome doesn't take the ended event anymore.
Quick fix:
setTimeout(function(){ [...] }, 1400);

Categories

Resources