Multiple errors when using video.currentTime - javascript

I am using this code to make a video player with custom controls. For some reason, I get an error telling me that my "seektimeupdate" and "vidseek" functions are not defined. I went into the console to see whether it will tell me where the error is but it doesn't tell me where.
var myvideo = document.getElementById("myvideo")
var button = document.getElementById('button')
var seekslider = document.getElementById('vidtime');
var isplaying = false;
function playvid() {
if (isplaying==false) {
myvideo.play();
button.innerText="Pause"
isplaying=true;
} else {
myvideo.pause();
button.innerText="Play"
isplaying=false;
}
function vidseek() {
var seekto = myvideo.duration * (seekslider.value / 100);
myvideo.currentTime = seekto;
}
function seektimeupdate() {
var nt = myvideo.currentTime * (100 / myvideo.duration)
seekslider.value=nt;
}
}
setInterval(seektimeupdate,10,false)
seekslider.addEventListener("change",vidseek,false)
body {
background-color: #42b0f4;
}
#videocontrols {
width:250px;
background-color: #8c93a5;
padding: 2px;
text-align: left;
}
#myvideo {
align-self: center;
background-color: #e2eaff;
width: 250px;
padding: 2px;
}
#vidtime {
width: 100px;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<video src="https://www.w3schools.com/html/mov_bbb.mp4" id="myvideo"></video>
<div id="videocontrols">
<font color="#8c93a5">cv</font><button id="button" onclick="playvid()" height="25">Play</button><input type="range" id="vidtime" value="0" min="0" max="100">
</div>
</body>
If you look at my main code you can tell it's a bit messy, but what this is supposed to be doing is changing the time relative to the sliderbar and updating the bar every 10 milliseconds, instead I am just getting a big error. Any help would be appreciated. Thanks in advance!

You had vidseek() and seektimeupdate() within playvid() function. Look at the code below:
var myvideo = document.getElementById("myvideo")
var button = document.getElementById('button')
var seekslider = document.getElementById('vidtime');
var isplaying = false;
function playvid() {
if (isplaying==false) {
myvideo.play();
button.innerText="Pause"
isplaying=true;
} else {
myvideo.pause();
button.innerText="Play"
isplaying=false;
}
}
/* vidseek() and seektimeupdate() should live outside of playvid() function */
function vidseek() {
var seekto = myvideo.duration * (seekslider.value / 100);
myvideo.currentTime = seekto;
}
function seektimeupdate() {
var nt = myvideo.currentTime * (100 / myvideo.duration)
seekslider.value=nt;
}
setInterval(seektimeupdate,10,false)
seekslider.addEventListener("change",vidseek,false)
body {
background-color: #42b0f4;
}
#videocontrols {
width:250px;
background-color: #8c93a5;
padding: 2px;
text-align: left;
}
#myvideo {
align-self: center;
background-color: #e2eaff;
width: 250px;
padding: 2px;
}
#vidtime {
width: 100px;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<video src="https://www.w3schools.com/html/mov_bbb.mp4" id="myvideo"></video>
<div id="videocontrols">
<font color="#8c93a5">cv</font><button id="button" onclick="playvid()" height="25">Play</button><input type="range" id="vidtime" value="0" min="0" max="100">
</div>
</body>

Related

Why can this function not use opacity?

I would like to make the image a little transparent for a short time by pressing the button and then make it visible again normally. Why does the code not work?
<!DOCTYPE html>
<html>
<head>
<style>
img {
width: 128px;
height: 128px;
padding: 10px;
}
img:hover {
opacity: 0.5;
}
</style>
</head>
<body>
<div id="epicenter">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/7/70/Face-devil-grin.svg/1024px-Face-devil-grin.svg.png" alt="Schwarz" id="black">
</div>
<button onclick="test()">Test</button>
<script>
function sleep(miliseconds) {
var currentTime = new Date().getTime();
while (currentTime + miliseconds >= new Date().getTime()) {
}
}
function test() {
document.getElementById("black").style.opacity = "0.33";
sleep(3000);
document.getElementById("black").style.opacity = "1";
}
</script>
</body>
</html>
Using setTimeout is much simpler.
function test() {
const el = document.getElementById('black');
el.style.opacity = '0.33';
setTimeout(() => el.style.opacity = '1', 3000);
}
img width: 128px height: 128px padding: 10px; }
img:hover { opacity: 0.5; }
<div id="epicenter">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/7/70/Face-devil-grin.svg/1024px-Face-devil-grin.svg.png" alt="Schwarz" id="black">
</div>
<button onclick="test()">Test</button>
You should use SetTimeout instead of defining your own sleep function.
setTimeout(function(){
document.getElementById("black").style.opacity = 1;
}, 3000);
Replace your sleep function call with the above.
Refer https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Timeouts_and_intervals for more details

Qr & Barcode Reader javascript documentation for html5

I want to make an input where it can be automatically filled in after scanning a QR or barcode scanner using a webcam or phone cam.
for the script I imagined something like this
<video autoplay = "true" id = "video-webcam">
</video>
<input type = "text" id = "scanresult">
<script>
external or internal script for scan qr or barcode. save result in variable = result
html DOM getElementById ('scanresult'). value (result);
</script>
I hope anyone can give me suggestions or feedback for my problem.
Thank you
Before it thank you for JaromandaX,
i have found script for barcode scanner on Html5 using webcam.
this is my index.html
<!DOCTYPE html>
<html>
<head>
<title>QR Code Scanner</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" />
<link rel="stylesheet" href="style.css" />
<script src="https://rawgit.com/sitepoint-editors/jsqrcode/master/src/qr_packed.js"></script>
</head>
<body>
<div id="container">
<h1>QR Code Scanner</h1>
<a id="btn-scan-qr">
<img src="https://dab1nmslvvntp.cloudfront.net/wp-content/uploads/2017/07/1499401426qr_icon.svg">
<a/>
<canvas hidden="" id="qr-canvas"></canvas>
<div id="qr-result" hidden="">
<b>Data:</b> <span id="outputData"></span>
</div>
</div>
<script src="qrCodeScanner.js"></script>
</body>
</html>
qsCodeScanner.js
//const qrcode = window.qrcode;
const video = document.createElement("video");
const canvasElement = document.getElementById("qr-canvas");
const canvas = canvasElement.getContext("2d");
const qrResult = document.getElementById("qr-result");
const outputData = document.getElementById("outputData");
const btnScanQR = document.getElementById("btn-scan-qr");
let scanning = false;
qrcode.callback = res => {
if (res) {
outputData.innerText = res;
scanning = false;
video.srcObject.getTracks().forEach(track => {
track.stop();
});
qrResult.hidden = false;
canvasElement.hidden = true;
btnScanQR.hidden = false;
}
};
btnScanQR.onclick = () => {
navigator.mediaDevices
.getUserMedia({ video: { facingMode: "environment" } })
.then(function(stream) {
scanning = true;
qrResult.hidden = true;
btnScanQR.hidden = true;
canvasElement.hidden = false;
video.setAttribute("playsinline", true); // required to tell iOS safari we don't want fullscreen
video.srcObject = stream;
video.play();
tick();
scan();
});
};
function tick() {
canvasElement.height = video.videoHeight;
canvasElement.width = video.videoWidth;
canvas.drawImage(video, 0, 0, canvasElement.width, canvasElement.height);
scanning && requestAnimationFrame(tick);
}
function scan() {
try {
qrcode.decode();
} catch (e) {
setTimeout(scan, 300);
}
}
style.css
html {
height: 100%;
}
body {
font-family: sans-serif;
padding: 0 10px;
height: 100%;
background: black;
margin: 0;
}
h1 {
color: white;
margin: 0;
padding: 15px;
}
#container {
text-align: center;
margin: 0;
}
#qr-canvas {
margin: auto;
width: calc(100% - 20px);
max-width: 400px;
}
#btn-scan-qr {
cursor: pointer;
}
#btn-scan-qr img {
height: 10em;
padding: 15px;
margin: 15px;
background: white;
}
#qr-result {
font-size: 1.2em;
margin: 20px auto;
padding: 20px;
max-width: 700px;
background-color: white;
}
There are lots of better libraries out there for doing this, but I'd personally recommend QrScanner because of its simplicity and intuitiveness.
Your live QrCode Scanner would be like this...
scanner.html
<div id="holder">
<h3>Scan QR Code from Camera</h3>
<div class="make">
<video id="scan"></video>
</div>
<div>
<input type = "text" id = "scanresult"><br>
<button id="start">Start</button>
<button id="stop">Stop</button>
</div>
</div>
Then add a little CSS as:
style.css
#holder{
width: 30%;
margin:auto;
}
#holder .make {
width: 99%;
height: 30vh;
margin-bottom: 15px;
text-align: center;
}
video {
width: 99%;
margin:auto;
}
Then add your QrScanner code as:
<script type="module">
import QrScanner from "/path/to/qr-scanner.min.js";
QrScanner.WORKER_PATH = "/path/to/qr-scanner-worker.min.js";
// Scanner Object
const scanner = new QrScanner(
document.getElementById("scan"),
function(result){
document.getElementById("scanresult").value = result;
}
);
document.getElementById("start").onclick = e => scanner.start();
document.getElementById("stop").onclick = e => scanner.stop();
</script>
Then connect your camera and click start button...

Using setInterval to create a progress bar

I was hoping a kind soul might be able to assist.
I have a slideshow which auto-plays, my intention is to have the next button act as a visual aid, highlighting the when the next frame is coming in.
sync with the autoPlay interval.
Right now, the update func concludes too early, which is the best I have managed to do. Typically I have the clearInterval and setInterval conflicting creating shuddering animations.
What am I doing wrong?
<!doctype html>
<html lang="en">
<head>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
.carousel_wrapper {
height: 50vh;
width: 100%;
position: relative;
}
.carousel_frame {
width: 100%; height: 100%;
}
.carousel_controls {
position: absolute;
bottom: 0;
left: 0;
}
.prev, .next {
height: 50px;
width: 100px;
background: aqua;
display: inline-block;
}
.next {
background: linear-gradient(to right, white 0%, aqua);
}
.carousel_frame:nth-child(1) {
background: red;
}
.carousel_frame:nth-child(2) {
background: blue;
}
.carousel_frame:nth-child(3) {
background: green;
}
</style>
<script>
window.addEventListener('DOMContentLoaded', () => {
const homepage_carousel = new carousel();
});
function carousel() {
const carousel = document.getElementsByClassName('.carousel_wrapper')[0];
const frames = [...document.getElementsByClassName('carousel_frame')];
const prev_button = document.getElementsByClassName('prev')[0];
const next_button = document.getElementsByClassName('next')[0];
this.frameIndex = 1;
prev_button.addEventListener('click', () => {
this.resetPlay();
this.move(-1);
})
next_button.addEventListener('click', () => {
this.resetPlay();
this.move(+1);
})
this.hideAll = () => {
frames.forEach((f) => {
f.style.display = 'none';
});
}
this.show = () => {
this.hideAll();
frames[this.frameIndex - 1].style.display = 'block';
this.update_bg();
}
this.move = (amount) => {
this.frameIndex += amount;
this.frameIndex = (this.frameIndex > frames.length ? 1 : (this.frameIndex < 1) ? frame.lengh : this.frameIndex);
this.show();
}
this.update_bg = () => {
let w = 1;
let test = setInterval(adjust, 10);
function adjust() {
if (w >= 100) {
clearInterval(test);
w = 0;
} else {
w++;
next_button.style.backgroundImage = `linear-gradient(to right, white ${w}%, aqua)`
}
}
setInterval(adjust, 3000);
}
this.autoPlay = () => {
this.move(+1)
this.update_bg();
}
this.resetPlay = () => {
// clearInterval(timer);
// timer = setInterval(this.autoPlay(), 4000);
}
this.show();
const timer = setInterval(this.autoPlay, 3000);
}
</script>
</head>
<body>
<div class='carousel_wrapper'>
<div class='carousel_frame'>
<span>Headline</span>
<span>Description</span>
<span>CTA</span>
</div>
<div class='carousel_frame'>
<span>Headline</span>
<span>Description</span>
<span>CTA</span>
</div>
<div class='carousel_frame'>
<span>Headline</span>
<span>Description</span>
<span>CTA</span>
</div>
<div class='carousel_controls'>
<span class='prev'>Previous</span>
<span class='next'>
Next
</span>
</div>
</div>
</body>
</html>

Javascript 'type error Uncaught TypeError: Cannot set property 'backgroundColor' of undefined' but works

I have an issue with the backgroundColor property in JavaScript but my function keeps working, regardless of the error.
Can somebody explain, how this is happening?
Fiddle link
Thank you
JavaScript Code with error:
function surligne(champ, erreur)
{
if(erreur)
{
champ.style.backgroundColor = "#fba";
document.getElementById("messageErreur").style.display ="block";
}
else
{
champ.style.backgroundColor = "";
document.getElementById("messageErreur").style.display ="none";
}
Here is your error:
champ.addEventListener("blur", verifMail);
function verifMail(champ) {
change it to this:
champ.addEventListener("blur", verifMail);
function verifMail() {
Champ is already defined at the top of the file, by adding a parameter on the verifyMail function, you make it so that the function can no longer view the the champ variable at the top of the file and instead it sees the blur event.
The reason it does change color is because you call verifMail from the verifForm function, passing the champ parameter.
The loss of focus triggers the blur. It is odd that the blur comes first.that's why on focus out your function again is calling so your error happened. I've correct it with variable value hope it'll help you
If you change the alerts to console.log (or something that does not steal focus), you will see that the events fire correctly.
var modal = document.getElementById('maPopin');
var btn = document.getElementById("monBouton");
var span = document.getElementsByClassName("fermer")[0];
var champ = document.getElementById("mail");
var erreur = true;
btn.addEventListener("click", function() {
modal.style.display = "block";
});
span.addEventListener("click", function() {
modal.style.display = "none";
});
window.addEventListener("click", function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
});
champ.addEventListener("blur", verifMail);
champ.addEventListener("focus", verifMail);
function verifMail(champ)
{
var regex = /^[a-zA-Z0-9._-]+#[a-z0-9._-]{2,}\.[a-z]{2,4}$/;
if(!regex.test(champ.value))
{
surligne(champ, true);
return false;
}
else
{
surligne(champ, false);
return true;
}
}
function surligne(champ, erreur)
{ if(champ.type !="focus" && champ.type !=="blur"){
if(erreur)
{
champ.style.backgroundColor = "#fba";
document.getElementById("messageErreur").style.display ="block";
}
else
{
champ.style.backgroundColor = "";
}
}
document.getElementById("messageErreur").style.display ="none";
}
/* } */
champ.addEventListener("keyup", verifForm);
function verifForm()
{
var mailOk = verifMail(champ);
if(mailOk)
{
document.getElementById('submit1').disabled=0;
return true;
}
else
{
document.getElementById('submit1').disabled=1;
return false;
document.getElementById("messageErreur").style.display ="none";
}
}
body {font-family: Arial, Helvetica, sans-serif;}
/* Background pop-in */
.popin {
display: none;
position: fixed;
z-index: 1;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0,0.4);
}
/* Style de la pop-in */
.popin-style {
background-color: #FFFFFF;
margin: auto;
padding: 20px;
border: 1px solid #529D93;
width: 35%;
}
/* Bouton fermer */
.fermer {
color: #3f3f3f;
float: right;
font-size: 40px;
font-weight: bold;
}
.bob-style
{
width: 50%;
height: auto;
display: block;
margin-left: auto;
margin-right: auto;
text-align: center;
}
.fermer:hover,
.fermer:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
#messageErreur
{
display: none;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="UTF-8">
</head>
<body>
<h2>Exemple de Pop-in</h2>
<button id="monBouton">Qui sommes nous ?</button>
<div id="maPopin" class="popin">
<div class="popin-style">
<span class="fermer">×</span>
<p>Cet objectif a été réalisé par Guillaume et Nicolas... Alias Bob et Patrick </p>
<img src="http://www.chamalow-shop.com/images/t/tds/TDS-bob-patrick-geek-vert-g.gif" class="bob-style">
<form>
<label for="email">Veuillez saisir votre email :</label>
<input type="text" name="email" id="mail" placeholder="Email...">
<button type="submit" id="submit1" disabled="disabled">Envoyer</button>
<p id="messageErreur">Adresse email incorrecte</p>
</form>
</div>
</div>
<script src="myscripts.js"></script>
</body>
</html>
champ.style.backgroundColor = "";
the background color should be set to some value, how can it be blank ?

TypeError: Cannot read property 'innerHTML' of null

I am trying to retain the best time value under the id "bestTime", but I keep on getting the following error in Chrome: Cannot read property 'innerHTML' of null at showBestTime.
Not sure what I am doing wrong, I have attached the code below. I am trying to process the best time in the function showBestTime. Thanks in advance!
<html>
<head>
<title>Reaction tester</title>
</head>
<style type="text/css">
#page-container{
width: 1000px;
margin: 0 auto;
height: 800px;
}
body{
margin: 0;
padding: 0;
font-family: Helvetica, Arial, freesans, sans-serif;
}
#shape{
width: 200px;
height: 200px;
background-color: red;
display: none;
position: relative;
}
.time{
font-weight: bold;
}
</style>
<body>
<div id="page-container">
<h1>Test Your Reactions!</h1>
<p>Click on the boxes and circles as quickly as you can!</p>
<p class="time">Your time: <span id="timeTaken"></span></p>
<p class="time">Best time: <span id="bestTime">10</span>s</p>
<div id="shape"></div>
</div>
<script type="text/javascript">
var start=new Date().getTime();
function getRandomColor() {
var letters= "0123456789ABCDEF";
var color= "#";
for (var i=0; i<6; i++) {
color +=letters[Math.floor(Math.random()*16)];
}
return color;
}
function makeShapeAppear(){
var top=Math.random()*400;
var left=Math.random()*800;
var width=(Math.random()*400)+100;
if(Math.random()>0.5){ document.getElementById("shape").style.borderRadius="50%";
} else{
document.getElementById("shape").style.borderRadius="0";
} document.getElementById("shape").style.backgroundColor=getRandomColor();
document.getElementById("shape").style.top=top+"px";
document.getElementById("shape").style.left=left+"px"; document.getElementById("shape").style.width=width+"px"; document.getElementById("shape").style.height=width+"px";
document.getElementById("shape").style.display="block";
start=new Date().getTime();
}
function appearAfterDelay(){
setTimeout(makeShapeAppear, (Math.random() * 2000));
}
function showBestTime(y){ if(y<document.getElementById("besttime").innerHTML){
document.getElementById("besttime").innerHTML=y;
}
}
appearAfterDelay();
document.getElementById("shape").onclick=function(){
document.getElementById("shape").style.display="none";
var end=new Date().getTime();
var timeTaken=(end-start)/1000; document.getElementById("timeTaken").innerHTML=timeTaken+"s";
appearAfterDelay();
showBestTime(timeTaken);
}
</script>
</body>
</html>
You have made a spelling mistake in your selector. You have provided besttime as your selector instead of bestTime. I have added the working code along with.
<html>
<head>
<title>Reaction tester</title>
</head>
<style type="text/css">
#page-container {
width: 1000px;
margin: 0 auto;
height: 800px;
}
body {
margin: 0;
padding: 0;
font-family: Helvetica, Arial, freesans, sans-serif;
}
#shape {
width: 200px;
height: 200px;
background-color: red;
display: none;
position: relative;
}
.time {
font-weight: bold;
}
</style>
<body>
<div id="page-container">
<h1>Test Your Reactions!</h1>
<p>Click on the boxes and circles as quickly as you can!</p>
<p class="time">Your time: <span id="timeTaken"></span></p>
<p class="time">Best time: <span id="bestTime">10</span>s</p>
<div id="shape"></div>
</div>
<script type="text/javascript">
var start = new Date().getTime();
function getRandomColor() {
var letters = "0123456789ABCDEF";
var color = "#";
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function makeShapeAppear() {
var top = Math.random() * 400;
var left = Math.random() * 800;
var width = (Math.random() * 400) + 100;
if (Math.random() > 0.5) {
document.getElementById("shape").style.borderRadius = "50%";
} else {
document.getElementById("shape").style.borderRadius = "0";
}
document.getElementById("shape").style.backgroundColor = getRandomColor();
document.getElementById("shape").style.top = top + "px";
document.getElementById("shape").style.left = left + "px";
document.getElementById("shape").style.width = width + "px";
document.getElementById("shape").style.height = width + "px";
document.getElementById("shape").style.display = "block";
start = new Date().getTime();
}
function appearAfterDelay() {
setTimeout(makeShapeAppear, (Math.random() * 2000));
}
function showBestTime(y) {
if (y < document.getElementById("bestTime").innerHTML) {
document.getElementById("bestTime").innerHTML = y;
}
}
appearAfterDelay();
document.getElementById("shape").onclick = function () {
document.getElementById("shape").style.display = "none";
var end = new Date().getTime();
var timeTaken = (end - start) / 1000;
document.getElementById("timeTaken").innerHTML = timeTaken + "s";
appearAfterDelay();
showBestTime(timeTaken);
}
</script>
</body>
</html>
You have span:
<span id="bestTime">
and you query it with
document.getElementById("besttime")
and bestTime is not equal to besttime, so change to:
document.getElementById("bestTime")

Categories