clicking seekbar restarts video instead of seeking - javascript

$('.video-player').each(function(_, videoPlayer) {
let eleVideoObj = $(videoPlayer).find("video");
let eleVideoSeekbar = $(videoPlayer).find(".video-seekbar");
let eleVideoProgress = $(eleVideoSeekbar).find(".progress");
let totalDurationInSeconds = 0;
let currentTimeInSeconds = 0;
let currentDuration = null;
let totalDuration = null;
$(eleVideoSeekbar).on('click', e => {
let tempSeekPosition =
e.pageX - videoPlayer.offsetLeft - eleVideoSeekbar['0'].offsetLeft;
let tempSeekValue = tempSeekPosition / eleVideoSeekbar['0'].clientWidth;
eleVideoObj['0'].currentTime = tempSeekValue * totalDurationInSeconds;
});
}
Ive been trying to look and see why it's restarting the video but i can't and haven't yet
I need to know why is causing this to happen because as you may have guessed it's going on my website
thanks in advance!

Ok i figured it out after messing with it and trying to figure it out
i removed the the videoPlayer instance now it goes
e.pageX - eleVideoSeekbar['0'].offsetLeft;
instead of
e.pageX - videoPlayer.offsetLeft - eleVideoSeekbar['0'].offsetLeft;
$('.video-player').each(function(_, videoPlayer) {
let eleVideoObj = $(videoPlayer).find("video");
let eleVideoSeekbar = $(videoPlayer).find(".video-seekbar");
let eleVideoProgress = $(eleVideoSeekbar).find(".progress");
let totalDurationInSeconds = 0;
let currentTimeInSeconds = 0;
let currentDuration = null;
let totalDuration = null;
$(eleVideoSeekbar).on('click', e => {
let tempSeekPosition =
e.pageX - eleVideoSeekbar['0'].offsetLeft;
let tempSeekValue = tempSeekPosition / eleVideoSeekbar['0'].clientWidth;
eleVideoObj['0'].currentTime = tempSeekValue * totalDurationInSeconds;
});```
}

Related

Video 'ended' .addEventListener no working

I worked on building this template using the javascript and I can't seem to get the video I have on the screen to activate an event once the video finishes. The page content is pulled in via JSON file. The "videoDemo1" is set to autoplay, so I hope I'm not call the eventListener before the video exist in the HTML document. If there's any questions, just ask, thanks. Here's my code:
function buildVideoContent(pageData) {
// build the layout
let layout = buildColumns(pageData.layout);
// get page container from DOM
let page = document.getElementById('page_frame');
// clear the page frame
page.innerHTML = "";
// main video container
let mainVidCont = document.createElement('div');
mainVidCont.id = "main-cont";
mainVidCont.classList.add('bg-height');
page.appendChild(mainVidCont);
// add video wrapper and video content (start video and end video)
let vidWrapper = document.createElement('div');
vidWrapper.id = "vDemoWrapper";
vidWrapper.classList.add('vid-wrapper-bg');
vidWrapper.innerHTML = "<video id='videoDemo1' controls autoplay muted loop class='video-bg'><source src='assets/media/0010.mp4' type='video/mp4'>Your browser does not support the video tag.</video><video id='videoDemo2' controls loop class='video-bg btn-hide'><source src='assets/media/0010.mp4' type='video/mp4'>Your browser does not support the video tag.</video>";
mainVidCont.appendChild(vidWrapper);
// create the containers for content and buttons
for(let i = 1; i <= 10; i++){
let innerContent = document.createElement('div');
innerContent.id = "aniContentInfo" + i + "";
innerContent.classList.add('inner-cont');
//innerContent.classList.add('animation-fadein');
innerContent.classList.add('col-4');
innerContent.classList.add('float-left');
mainVidCont.appendChild(innerContent);
}
let sumDiv1 = document.getElementById('aniContentInfo1');
let sumDiv2 = document.getElementById('aniContentInfo2');
let sumDiv3 = document.getElementById('aniContentInfo3');
let sumDiv4 = document.getElementById('aniContentInfo4');
let sumDiv5 = document.getElementById('aniContentInfo5');
let sumDiv6 = document.getElementById('aniContentInfo6');
let sumDiv7 = document.getElementById('aniContentInfo7');
let sumDiv8 = document.getElementById('aniContentInfo8');
let sumDiv9 = document.getElementById('aniContentInfo9');
let sumDiv10 = document.getElementById('aniContentInfo10');
let viewerText1 = buildContentCard(pageData.content1.text_elements, false);
let viewerText2 = buildContentCard(pageData.content2.text_elements, false);
let viewerText3 = buildContentCard(pageData.content3.text_elements, false);
let viewerText4 = buildContentCard(pageData.content4.text_elements, false);
let viewerText5 = buildContentCard(pageData.content5.text_elements, false);
let viewerText6 = buildContentCard(pageData.content6.text_elements, false);
let viewerText7 = buildContentCard(pageData.content7.text_elements, false);
let viewerText8 = buildContentCard(pageData.content8.text_elements, false);
let viewerText9 = buildContentCard(pageData.content9.text_elements, false);
let viewerText10 = buildContentCard(pageData.content10.text_elements, false);
sumDiv1.appendChild(viewerText1);
sumDiv2.appendChild(viewerText2);
sumDiv3.appendChild(viewerText3);
sumDiv4.appendChild(viewerText4);
sumDiv5.appendChild(viewerText5);
sumDiv6.appendChild(viewerText6);
sumDiv7.appendChild(viewerText7);
sumDiv8.appendChild(viewerText8);
sumDiv9.appendChild(viewerText9);
sumDiv10.appendChild(viewerText10);
// create buttons and add them to content container
for(let v = 1; v <= 10; v++){
let continueBtn = document.createElement('BUTTON');
continueBtn.id = "continue-btn" + v + "";
continueBtn.classList.add('btn-primary');
continueBtn.classList.add('btn');
continueBtn.innerHTML = "CONTINUE";
let paraCont = document.getElementById("aniContentInfo" + v + "");
paraCont.appendChild(continueBtn);
for(let c = 1; c <= 9; c++){
let count = document.getElementById("aniContentInfo" + c + "");
count.classList.add('btn-hide');
}
if(v = 10){
document.getElementById("aniContentInfo10").classList.add('animation-fadein');
}
};
// THE CODE COMMENTED OUT BELOW ARE ADDITIONAL EVENTLISTENERS THAT I'VE TRIED
/* document.addEventListener('DOMContentLoaded', () => {
var vid = document.getElementById("videoDemo1");
vid.onended = function() {
document.getElementById("aniContentInfo10").classList.add('animation-fadein');
};
if ( video.readyState === 4 ) {
let vid = document.getElementById('videoDemo1');
vid.addEventListener("ended", function(e){
if(state === 0){
let videoElement = document.getElementById('videoDemo1');
videoElement.classList.add('vid-opacity');
}
});
}
}); */
// BELOW IS WHERE I WROTE THE ADDEVENTLISTENER
document.getElementById('videoDemo1').addEventListener('ended',myHandler,false);
function myHandler(e) {
// What you want to do after the event
document.getElementById("aniContentInfo10").classList.add('animation-fadein');
};
// APPARENTLY THIS DOESN'T WORK WHEN I RUN THE CODE
// create click events for each button to proceed to next content container
for(let h = 1; h <= 10; h++){
continueBtn = document.getElementById('continue-btn' + h + '');
document.getElementById('continue-btn' + h + '').addEventListener("click", function userProgression(e){
let subOne = h - 1;
let videoElement = document.getElementById('videoDemo1');
videoElement.classList.remove('vid-opacity');
videoElement.classList.add('vid-visible');
let videoElement2 = document.getElementById('videoDemo2');
videoElement2.classList.remove('btn-hide');
videoElement2.classList.add('btn-show');
// remove button and content from screen to reveal new content container
setTimeout(function(){
let hMinus = h - 1;
let contentInnerNum = document.getElementById('aniContentInfo' + h + '');
contentInnerNum.classList.remove('btn-hide');
contentInnerNum.classList.remove('animation-fadein');
contentInnerNum.classList.add('animation-fadeout');
if(hMinus !== 0){
let contentNumMinus = document.getElementById('aniContentInfo' + hMinus + '');
contentNumMinus.classList.remove('btn-hide');
contentNumMinus.classList.add('animation-fadein');
contentNumMinus.classList.remove('animation-fadeout');
}
let contentBtn = document.getElementById('continue-btn' + h + '');
contentBtn.classList.add('animation-fadeout');
let contentInner = document.getElementById('continue-btn' + subOne + '');
contentInner.classList.remove('btn-hide');
contentInner.classList.remove('btn-show');
contentInner.classList.add('btn-center');
}, 3000);
// add classes to content elements from the above lines to to remove them completely
setTimeout(function(){
let topBtn = document.getElementById('continue-btn' + h + '');
topBtn.classList.add('btn-hide');
let contentInner = document.getElementById('aniContentInfo' + h + '');
contentInner.classList.add('btn-hide');
}, 6000);
// set timer to make next second video visible.
setTimeout(function(){
let hMinus = h - 1;
if(hMinus !== 0){
let videoElement1a = document.getElementById('videoDemo1');
videoElement1a.classList.remove('vid-opacity');
videoElement1a.classList.add('vid-visible');
}
let videoElement2 = document.getElementById('videoDemo2');
videoElement2.classList.remove('btn-show');
videoElement2.classList.add('btn-hide');
}, 8000);
// important! bring back original first video at the exact second the second video ends
setTimeout(function(){
let videoElement1b = document.getElementById('videoDemo1');
videoElement1b.classList.remove('vid-visible');
videoElement1b.classList.add('vid-opacity');
}, 60000);
});
}
// I ALSO TRIED PLACING THE EVENTLISTENER HERE, BUT NO LUCK
/* document.addEventListener("DOMContentLoaded", function(event) {
let vid1 = document.getElementById("videoDemo1");
if ( vid1.readyState === 4 ) {
vid1.onended = () => {
vid1.classList.add('vid-opacity');
};
}
});*/
}
If it's something I'm missing, any help would be appreciated, thanks

I have a misunderstanding with localStorage

I'm currently beginning to learn how to use javascript, and I have a small problem.
I'm making a minigame of 'find the random number', and I'm trying to implement a localStorage savestate that let me keep my game as it was when I closed it, but without success. Here's the part of my JS
where I'm stuck.
let Rndm = Math.floor(Math.random() * 100) + 1;
var tentatives = document.querySelector('.tentatives');
var resultat = document.querySelector('.resultat');
var plusoumoins = document.querySelector('.plusoumoins');
var valider = document.querySelector('.valider');
var essai = document.querySelector('.essai');
var nmbrmax = 1000;
var nmbrtent = 1;
let j1 = document.getElementById("j1");
let j2 = document.getElementById("j2");
var joueur1 = document.getElementById("joueur1");
var joueur2 = document.getElementById("joueur2");
let nomsjoueurs = document.getElementById("nomsjoueurs");
let tour = document.getElementById("tour");
var playerTurn = 0;
const partiesauvee = []
function sauvegarder() {
partiesauvee.push(tentatives.textContent);
partiesauvee.push(resultat.textContent);
partiesauvee.push(plusoumoins.textContent);
partiesauvee.push(nmbrmax);
partiesauvee.push(nmbrtent);
partiesauvee.push(joueur1.value);
partiesauvee.push(joueur2.value);
localStorage.setItem('sauvegard', JSON.stringify(partiesauvee))
}
function refresh() {
const partiesauvee = JSON.parse(localStorage.getItem('sauvegard'));
var tentatives = JSON.parse(localStorage.getItem('sauvegard'));
var resultat = JSON.parse(localStorage.getItem('sauvegard'));
var plusoumoins = JSON.parse(localStorage.getItem('sauvegard'));
var nmbrmax = localStorage.getItem('sauvegard');
var nmbrtent = localStorage.getItem('sauvegard');
var joueur1 = JSON.parse(localStorage.getItem('sauvegard'));
var joueur2 = JSON.parse(localStorage.getItem('sauvegard'));
}
window.addEventListener('DOMContentLoaded', refresh);
When the sauvegarder function is activated, the console.log(localstorage) find all the values,
but I can't find a way to return them to their places. Someone have an idea? Thanks !
You're storing an array. You need to assign each array element to a different DOM element.
function refresh() {
const storage = localStorage.getItem('sauvegard');
if (!storage) { // nothing saved
return;
}
const partiesauvee = JSON.parse(storage);
tentatives.textContent = partiesauvee[0];
resultat.textContent = partiesauvee[1];
plusoumoins.textContent = partiesauvee[2];
nmbrmax.textContent = partiesauvee[3];
nmbrtent.textContent = partiesauvee[4];
joueur1.textContent = partiesauvee[5];
joueur2.textContent = partiesauvee[6];
}

Can someone explain the logic behind this? Why in the 'for' loop is it <12? How can the i var be over 2 in the array?

I see this similar question asked in the java section. But i am just using 1 for loop. Why in the for() loop is it i<12?? I am not understanding the logic of that. There are only 3 variables in the episodes array. Can someone lead me in the right direction to understand this? I was just doing some practice on openclassroom.com.
class Episode {
constructor(title, duration, hasBeenWatched) {
this.title = title;
this.duration = duration;
this.hasBeenWatched = hasBeenWatched;
}
}
let firstEpisode = new Episode('Dark Beginnings', 45, true);
let secondEpisode = new Episode('The Mystery Continues', 45, false);
let thirdEpisode = new Episode('An Unexpected Climax', 60, false);
// Create your array here
// ====================================
let episodes = [firstEpisode, secondEpisode, thirdEpisode];
// ====================================
const body = document.querySelector('body');
for(let i = 0; i < 12; i++) { //this <12 i don't understand
let newDiv = document.createElement('div');
newDiv.classList.add('series-frame');
let newTitle = document.createElement('h2');
newTitle.innerText = 'The Story of Tau';
let newParagraph = document.createElement('p');
newParagraph.innerText = `${episodes[i].title}
${episodes[i].duration} minutes
${episodes[i].hasBeenWatched ? 'Already been watched' : 'Not yet watched'}`;
newDiv.append(newTitle);
newDiv.append(newParagraph);
body.append(newDiv);
}
There is no sense of using 12 in forLoop. However you can use episodes.length to iterate over episodes array
class Episode {
constructor(title, duration, hasBeenWatched) {
this.title = title;
this.duration = duration;
this.hasBeenWatched = hasBeenWatched;
}
}
let firstEpisode = new Episode('Dark Beginnings', 45, true);
let secondEpisode = new Episode('The Mystery Continues', 45, false);
let thirdEpisode = new Episode('An Unexpected Climax', 60, false);
// Create your array here
// ====================================
let episodes = [firstEpisode, secondEpisode, thirdEpisode];
// ====================================
const body = document.querySelector('body');
for(let i = 0; i < episodes.length; i++) { //this <12 i don't understand
let newDiv = document.createElement('div');
newDiv.classList.add('series-frame');
let newTitle = document.createElement('h2');
newTitle.innerText = 'The Story of Tau';
let newParagraph = document.createElement('p');
newParagraph.innerText = `${episodes[i].title}
${episodes[i].duration} minutes
${episodes[i].hasBeenWatched ? 'Already been watched' : 'Not yet watched'}`;
newDiv.append(newTitle);
newDiv.append(newParagraph);
body.append(newDiv);
}

I am trying to make an update engine with JS but I don't know what i'm doing wrong

let currentVersion ="CV";
let newVersion ="NV";
let currentVersionP = currentVersion.split('.');
let newVersionP = newVersion.split('.');
let i = 0;
if (isNaN(currentVersionP)) var _return = "0Masking";
else if (isNaN(newVersionP)) var _return = "0Masking";
if (newVersionP > currentVersionP) var _return = "UpdateAvailable";
if (newVersionP < currentVersionP) var _return = "RollbackAvailable";
if (newVersionP = currentVersionP) var _return = "NoChanges";
document.write(_return);
I Am trying to make an update engine for a Siri Shortcuts shortcut. But I don’t know what I am doing wrong. Someone please help me to change it that it work

A function doesn't respond in ref.on() even if the result is correct

I have been trying to create an app named workspace. I had asked another question earlier but now the features I have added are more. There is a remarks system. I have tried using different versions of my code and the code I have given has the best version I created. I cannot find an answer to my question on the net so I had to ask it here.
var ref = firebase.database().ref();
function stdRemarks(studentName){
let finalStuff;
ref.on("value", function(snapshot){
let keys = Object.keys(snapshot.val().schools[returnCurrentUser()][studentName]['remarks']);
for(i=0;i<keys.length;i++){
let objectToDealWith = snapshot.val().schools[returnCurrentUser()][studentName]['remarks'];
let remark = objectToDealWith[keys[i]]['remark'];
let examiner = objectToDealWith[keys[i]]['examiner'];
let fullRemark = ` ${examiner}: ${remark} | `
finalStuff += fullRemark;
}
return finalStuff;
});
}
ref.on("value", function(snapshot){
let dashTab = document.getElementById("dashboard_table");
let btn = document.getElementById("csv_blob");
let btn2 = document.getElementById("json_view");
let btn3 = document.getElementById("json_export");
btn.style.display = "block";
btn2.style.display = "block";
$("#json_export").css('display', 'block');
dashTab.innerHTML = "<thead><tr><th>Student Name</th><th>Class</th><th>Email</th><th>Subject</th><th>Project Info</th><th>Remarks</th><th>Project</th><th style='display: none;'>Project Download URL</th><th>Add Remark</th></tr></thead>";
let jsonRecieved = snapshot.val();
let objectToDealWith = snapshot.val().schools[returnCurrentUser()];
let lengthOfIt = Object.size(objectToDealWith);
for(i=0;i<lengthOfIt;i++){
let int = i + 1;
let names = Object.keys(objectToDealWith);
let stdName = names[i];
let finalResult = objectToDealWith[stdName];
document.getElementById("schoolnameis").innerText = "Dashboard - " + objectToDealWith['i'];
let stdClass = finalResult['class'];
let stdEmail = finalResult['email'];
let stdSubject = finalResult['subject'];
let stdiName = finalResult['stdname'];
let stdProjectName = finalResult['projectname']
let stdProjectInfo = finalResult['projectinfo'];
let stdProjectLink = finalResult['projectlink'];
console.log(stdRemarks(stdiName))
let elementToPush = `<tr><td>${stdiName.replace(/undefined/g, '')}</td><td>${stdClass.replace(/undefined/g, '')}</td><td>${stdEmail.replace(/undefined/g, '')}</td><td>${stdSubject.replace(/undefined/g, '')}</td><td>${stdProjectInfo.replace(/undefined/g, '')}</td><td>${stdRemarks(stdnameName).replace(/undefined/g, '')}</td><td><a href=${stdProjectLink}>${stdProjectName.replace(/undefined/g, '')}</a></td><td style='display:none;'>${stdProjectLink}</td><td id="${stdName}" style='text-align:center;' onclick="closeThatSomeThing();getIdOfTd(this.id)">&#x2795</td></tr>`;
dashTab.innerHTML += elementToPush;
}
});
So everything is working fine but some stuff here seems to corrupt the whole code. My database looks somewhat like this
Here is the error.
//A warning by firebase.
#firebase/database: FIREBASE WARNING: Exception was thrown by user callback. TypeError: Cannot read property 'replace' of undefined
//An error occuring on the variable `elementToPush` and its part ${stdRemarks(stdnameName).replace(/undefined/g, '') in the code.
Cannot read property 'replace' of undefined
I have to submit this project tomorrow.
your function 'stdRemarks' has a return type of 'void'. either return the the complete ref.on() or move 'finalstuff' outside the .on() function call and make sure the function 'stdRemarks' has the desired return type. in this case this would be a 'string';
function stdRemarks(studentName){
let finalStuff = "";
ref.on("value", function(snapshot){
let keys = Object.keys(snapshot.val().schools[returnCurrentUser()][studentName]['remarks']);
for(i=0;i<keys.length;i++){
let objectToDealWith = snapshot.val().schools[returnCurrentUser()][studentName]['remarks'];
let remark = objectToDealWith[keys[i]]['remark'];
let examiner = objectToDealWith[keys[i]]['examiner'];
let fullRemark = ` ${examiner}: ${remark} | `
finalStuff += fullRemark;
}
});
return finalStuff;
}
I made it work by using this code.
ref.on("value", function(snapshot){
let dashTab = document.getElementById("dashboard_table");
let btn = document.getElementById("csv_blob");
let btn2 = document.getElementById("json_view");
let btn3 = document.getElementById("json_export");
btn.style.display = "block";
btn2.style.display = "block";
$("#json_export").css('display', 'block');
dashTab.innerHTML = "<thead><tr><th>Student Name</th><th>Class</th><th>Email</th><th>Subject</th><th>Project Info</th><th>Remarks</th><th>Project</th><th style='display: none;'>Project Download URL</th><th>Add Remark</th></tr></thead>";
let jsonRecieved = snapshot.val();
let objectToDealWith = snapshot.val().schools[returnCurrentUser()];
let lengthOfIt = Object.size(objectToDealWith)-1;
for(i=0;i<lengthOfIt;i++){
let finalRemark;
let int = i + 1;
let names = Object.keys(objectToDealWith);
let stdName = names[i];
let finalResult = objectToDealWith[stdName];
let stdClass = finalResult['class'];
let stdEmail = finalResult['email'];
let stdSubject = finalResult['subject'];
let stdiName = finalResult['stdname'];
for(var e=0;e<Object.size(objectToDealWith[stdName]['remarks']);e++){
let keys = Object.keys(objectToDealWith[stdName]['remarks']);
let remark = objectToDealWith[stdName]['remarks'][keys[e]]['remark'];
let examiner = objectToDealWith[stdName]['remarks'][keys[e]]['examiner'];
let completeRemark = ` | ${examiner} : ${remark} `
finalRemark += completeRemark;
}
let stdProjectName = finalResult['projectname']
let stdProjectInfo = finalResult['projectinfo'];
let stdProjectLink = finalResult['projectlink'];
let elementToPush = `<tr><td>${stdiName}</td><td>${stdClass}</td><td>${stdEmail}</td><td>${stdSubject}</td><td>${stdProjectInfo}</td><td>${finalRemark.replace(/undefined/g, '')}</td><td><a href=${stdProjectLink}>${stdProjectName}</a></td><td style='display:none;'>${stdProjectLink}</td><td id="${stdName}" style='text-align:center;' onclick="closeThatSomeThing();getIdOfTd(this.id)">&#x2795</td></tr>`;
dashTab.innerHTML += elementToPush;
}
});
What i did here was that i turned i to e in the second loop and it worked...

Categories

Resources