I want to let the user click a button to loop a HTML5 video at a specified start time, which is not 0, and a specified end time, which is not the end of the whole video.
I don't want to force the video to be a certain length permanently. I want to eventually give the user multiple buttons to let them loop over different intervals of the video.
It works in Firefox, but not in Chrome. No errors are thrown but it seems that Chrome doesn't register my currentTime
assignments. It will begin at 0, not the specified start time, but it will end at the specified end time. It loops. The problem is just the start time.
SSCCE:
HTML:
<body>
<video src="./example.mp4" width="480" controls></video>
<div><button id="storyText">Loop</button></div>
</body>
JS:
$(document).ready(function() {
var video = document.getElementsByTagName('video')[0];
var timeStamp = [7, 11];
$('button').click(function() {
playVideoInterval(timeStamp[0], timeStamp[1]);
});
function playVideoInterval(start, end) {
video.addEventListener('timeupdate', loop);
video.currentTime = start;
document.body.addEventListener('click', endLoop, true);
video.play();
function loop() {
if (this.currentTime >= end) {
video.currentTime = start;
video.play();
}
}
function endLoop() {
video.pause();
document.body.removeEventListener('click', endLoop);
video.removeEventListener('timeupdate', loop);
}
}
});
EDIT: I have also attempted to enclose the code in my document.ready function in an event listener that listens for canplay
event or loadedmetadata
event. Neither help.
JS:
$(document).ready(function() {
var video = document.getElementsByTagName('video')[0];
var timeStamp = [7, 11];
video.addEventListener('canplay', execute);
function execute() {
video.removeEventListener('canplay', execute);
$('button').click(function() {
playVideoInterval(timeStamp[0], timeStamp[1]);
});
function playVideoInterval(start, end) {
video.addEventListener('timeupdate', loop);
video.currentTime = start;
document.body.addEventListener('click', endLoop, true);
video.play();
function loop() {
if (this.currentTime >= end) {
video.currentTime = start;
video.play();
}
}
function endLoop() {
video.pause();
document.body.removeEventListener('click', endLoop);
video.removeEventListener('timeupdate', loop);
}
}
}
});
EDIT: I'm using a server to serve it at localhost and this is where it is having problems. If I open the static page direct in the web browser, it is fine.