Javascript: Error loading a video, but just on Chrome - javascript

I have an HTML page that loads a video and display a download progress bar.
The video element is created like this:
function createVideo() {
var video = document.createElement("VIDEO");
video.setAttribute('controls', '');
video.setAttribute('preload', 'auto');
video.setAttribute('width', width);
video.setAttribute('id', 'video');
var source = document.createElement("SOURCE");
source.setAttribute('src', "https://www.example.com/video.mp4");
source.setAttribute('type', 'video/mp4');
video.addEventListener('progress', function() {
var endBuf = this.buffered.end(0); //1
var soFar = parseInt(((endBuf / this.duration) * 100));
var progressBar = document.getElementById("progressBar");
if (soFar < 100) {
progressBar.setAttribute('value', soFar);
} else {
progressBar.style = "display:none;";
}
});
The behavior I have on browsers is like this:
Safari shows the video page but the video does not auto play. No error is shown on console.
Firefox autoplays the video and shows no error on console.
Chrome autoplays the video and shows this error on console:
2codes.js:368 Uncaught DOMException: Failed to execute 'end' on 'TimeRanges': The index provided (0) is greater than or equal to the maximum bound (0).
at HTMLVideoElement. (https://example.com/code.js:368:32)
(anonymous) # functions.js:368
Line 368 is the one marked with //1 on the code above.
How do I solve that?

It's possible that Chrome is triggering your "progress" listener before the video is completely loaded and meaning that this.buffered has no TimeRanges yet. You might consider wrapping the body of your "progress" listener in an statement to handle if buffered has no TimeRanges specified:
video.addEventListener('progress', function() {
if(this.buffered.length > 0) {
var endBuf = this.buffered.end(0);
var soFar = parseInt(((endBuf / this.duration) * 100));
var progressBar = document.getElementById("progressBar");
if (soFar < 100) {
progressBar.setAttribute('value', soFar);
} else {
progressBar.style = "display:none;";
}
} else {
progressBar.style = "display:none;";
}
});

Related

HTML audio duration not working in chrome

Upong calling audioElement.duraion returns infinite in chromium based browsers but works find in firefox. The song is stored locally in the same directory.
console.log("Welcome to Spotify | clone");
let songIndex = 0;
const masterPlay = document.getElementById("masterPlay");
const progressBar = document.getElementById("progressBar");
const gif = document.getElementById("gif");
const audioElement=document.getElementById("song")
// let audioElement=new Audio('./1.mp3')
// Handeling play pause and click
masterPlay.addEventListener('click', () => {
if (audioElement.paused || audioElement.currentTime <= 0) {
audioElement.play();
masterPlay.classList.remove("fa-circle-play");
masterPlay.classList.add("fa-circle-pause");
gif.style.opacity = 1;
}
else {
audioElement.pause();
masterPlay.classList.remove("fa-circle-pause");
masterPlay.classList.add("fa-circle-play");
gif.style.opacity = 0;
}
});
//EventListeners
audioElement.addEventListener("timeupdate", () => {
progress = ((audioElement.currentTime / audioElement.duration) * 100);
progressBar.value = progress;
console.log(audioElement.currentTime)
});
Expectations:
It returns the duration of the autio track.
What I tried:
Different browsers. (Works fine on firefox based browsers.)
Different song. (I found that some songs don't work on chrome but on firefox everything works.)
Tried using HTML audio element. (The problem persists)
Tried using JS audio(). (The problem still exists)
At the end of the day I found out that it was a bug with VS code Live Preview extension from Microsoft

How do I hide a div or image after 20 seconds of flashing in Javascript?

I am busy making a memory game, where an image is to be displayed to the user, and after some 10 seconds of the image flashing, it should hide and four options are to be shown for the user to choose either the correct or incorrect answer.
So far, all I have accomplished is to load the images and cycle through all the puzzles that my code can find.
What I'm trying to do now is to make the image flash and hide after some time, while also just refreshing that section of the page, and not the entire page.
I am using C# and a user control on my page.
What I have tried so far is only
<script>
var x;
function BlinkImage() {
x = 1;
setInterval(change, 2000);
}
function change() {
if (x === 1) {
var image = document.getElementById('<%=imgMain.ClientID %>');
image.visible = false;
x = 2;
}
else {
var image = document.getElementById('<%=imgMain.ClientID %>');
image.visible = true;
x = 1;
}
}
</script>
And on loading my puzzle for that instance (in code behind)
Page.ClientScript.RegisterStartupScript(typeof(game), "Start", "<script language=javascript> BlinkImage(); </script>");
Which does fire, as I can step through the code in debugging on Firefox. But my image does not flash or blink. I understand I am just using visiblity as my "blinker". I don't know what else to use exactly.
What can I do to make the image flash or blink for, say 20 seconds, then hide the image after that time has passed? Then repeat the process once the user has made a choice.
You can try the following (comments in code):
var blinkInterval = setInterval(change, 2000), // set the interval into a variable
image = document.getElementById('test'), // replace test with your client id: <%=imgMain.ClientID %>
x = 1;
function change() {
if (x % 2 === 1) { // see if it is odd or even by modding by 2 and getting remainder
image.style.display = 'none';
} else {
image.style.display = 'block';
}
x++; // increment x
if (x === 10) { // should have happened 10 times (which is 20 seconds with your intervals being at 2 seconds)
clearInterval(blinkInterval); // clear the interval (should end hidden as odd is display none and we clear beforethe 20th is run)
}
}
<div id="test">test</div>
After the code has finished, wherever the user is making their selection, you just need to reset the blinkInterval variable:
blinkInterval = setInterval(change, 2000); // notice no need for the var declaration when you reset this
Use style attribute and change if visible/hidden
function change() {
var image = document.getElementById('<%=imgMain.ClientID %>');
//check if visible
if (image.style.visibility=="visible") {
image.style.visibility="hidden";
}
else {
image.style.visibility="visible";
}
}
;
Try this:
function flashAndHide(img_id){
var img = $("#"+img_id);
var x = 0;
var inter = setInterval(function(){
if(x % 2 == 0){
img.hide();
}else{
img.show();
}
x += 1;
}
},1000);
if(x === 20){
img.hide();
clearInterval(inter);
}
}
Haven't tested this, but it should work,

html 5 video tracking with percentage

how to track the status of video watched or not
if I write like this after 60%, I can send an ajax call and update the status to watched 60%
var i=0;
$("#video").bind("timeupdate", function(){
var currentTime = this.currentTime;
if(currentTime > 0.66*(this.duration)) {
if(i<1) {
/* Watched 66% ajax call will be here*/
}
i=i+1; //Reset for duplicates
}
});
Similarly.
if I write like this after 100% I can send an ajax call and update the status to completely watched 100%
$("#video").bind("ended", function() {
if(j<1) {
/* Watched 100% Finished */
}
j=j+1; //Reset for duplicates
});
But when someone forwarded the video to 90% and started playing from there then also 100% ajax call will trigger so what is the logic should I use to update the status to not watched in this case.
How about manipulating the functions like this
var watchPoints = [];
$("#video").bind("timeupdate", function(){
var currentTime = this.currentTime;
var watchPoint = Math.floor((currentTime/this.duration) * 100);
if(watchPoints.indexOf(watchPoint) == -1){
watchPoints.push(Math.floor(watchPoint))
}
});
/* Assuming that this will be called regardless of whether the user watches till the end point */
$("#video").bind("ended", function() {
/* use the watchPoints array to do the analysis(ordered array)
Eg.1 [1,2,3,4,5....100] - length is 100
2.[90,91..100] - length is only 10 and the starting point is 90
3.[1,2,3,4,5,50,51,52,61,62,63,64,65,66,67,68,69,70,98,99,100] - length is 21 and the index of 66 is 13 which clearly tells the user has skipped most of the parts
*/
});
With the research and little hard work i got the solution like this:
my HTML is this:
<div id="videoData">
<video width="75%" style="max-width: 60em;" autoplay="" controls="" class="center-block" id="video">
<source type="video/mp4" src="http://amerytech.net/lc_production/uploads/course_videos/Time Speed & Distance/Time Speed & Distance.mp4" le="max-width: 60em;" sty="">
</source>
</video>
</div>
<p id="display">asdddddd</p>
my javascript is this:
$(document).ajaxStop(function() {
var video = document.querySelector('video');
if (video) {
video.addEventListener("loadedmetadata", function() {
totalTime = this.duration;
});
$("#video").bind("timeupdate", function() {
var currentTime = this.currentTime;
var totalPlayed = 0;
var played = video.played;
for (var i = 0; i < played.length; i++) {
totalPlayed += played.end(i) - played.start(i);
console.log(totalPlayed);
$("#display").html(totalPlayed);
}
});
} else {
alert("not coming");
}
});

addEventListener 'playing' only fires once.

I have the following script which gets all video elements on a given page and then applies a playing event to them:
var video = document.getElementsByTagName("video");
for(var i = 0; i < video.length; i++){
(function(vid) {
vid.addEventListener('playing', function(){
var percentComplete = Math.round((vid.currentTime / vid.duration) * 100);
console.log(percentComplete);
});
})
(video[i]);
}
Now when I run the page and click on video 1 for example I see the percentComplete being logged to the console log, however when video 1 finishes and I click video 2 nothing is written to the console, it seems this addEventListener is only applied to the first video that is clicked, can someone explain why and how I can resolve this so it fires every time a video is played?
Try removing the outer closure and using event.target within your listener.
var video = document.getElementsByTagName("video");
for (var i = 0; i < video.length; i++) {
video[i].addEventListener('playing', function (event) {
var vid = event.target
var progress = Math.round((vid.currentTime / vid.duration) * 100)
console.log(progress)
})
}
For anyone interested, here's the full list of media events.

javascript preloader/progress/percentage

I'm having trouble finding any good information on how to make a javascript(or jquery) progress bar WITH text that tells you the percentage.
I don't want a plug in, I just want to know how it works so that I can adapt it to what I need. How do you preload images and get a variable for the number of images that are preloaded. Also, how do you change html/css and-or call a function, based on the number of images that are loaded already?
<img> elements have an onload event that fires once the image has fully loaded. Therefore, in js you can keep track of the number of images that have loaded vs the number remaining using this event.
Images also have corresponding onerror and onabort events that fire when the image fails to load or the download have been aborted (by the user pressing the 'x' button). You also need to keep track of them along with the onload event to keep track of image loading properly.
Additional answer:
A simple example in pure js:
var img_to_load = [ '/img/1.jpg', '/img/2.jpg' ];
var loaded_images = 0;
for (var i=0; i<img_to_load.length; i++) {
var img = document.createElement('img');
img.src = img_to_load[i];
img.style.display = 'hidden'; // don't display preloaded images
img.onload = function () {
loaded_images ++;
if (loaded_images == img_to_load.length) {
alert('done loading images');
}
else {
alert((100*loaded_images/img_to_load.length) + '% loaded');
}
}
document.body.appendChild(img);
}
The example above doesn't handle onerror or onabort for clarity but real world code should take care of them as well.
What about using something below:
$('#btnUpload').click(function() {
var bar = document.getElementById('progBar'),
fallback = document.getElementById('downloadProgress'),
loaded = 0;
var load = function() {
loaded += 1;
bar.value = loaded;
/* The below will be visible if the progress tag is not supported */
$(fallback).empty().append("HTML5 progress tag not supported: ");
$('#progUpdate').empty().append(loaded + "% loaded");
if (loaded == 100) {
clearInterval(beginLoad);
$('#progUpdate').empty().append("Upload Complete");
console.log('Load was performed.');
}
};
var beginLoad = setInterval(function() {
load();
}, 50);
});
JSFIDDLE
You might also want to try HTML5 progress element:
<section>
<p>Progress: <progress id="p" max=100><span>0</span>%</progress></p>
<script>
var progressBar = document.getElementById('p');
function updateProgress(newValue) {
progressBar.value = newValue;
progressBar.getElementsByTagName('span')[0].textContent = newValue;
} </script>
</section>
http://www.html5tutorial.info/html5-progress.php

Categories