Why is replaceChild cause problems? - javascript

function httpGet(theUrl) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", theUrl, false); // false for synchronous request
xmlHttp.send(null);
return xmlHttp.responseText;
}
var videosT = httpGet("https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=abcxyz&maxResults=6&order=date&type=video&key=abcxyz");
const videos = JSON.parse(videosT);
for (let step = 0; step < 6; step++) {
fetch('js/videos.html')
.then(res => res.text())
.then(text => {
let oldelem = document.getElementById("vid_" + step);
let newelem = document.createElement("div");
newelem.innerHTML = text;
oldelem.parentNode.replaceChild(newelem, oldelem);
})
}
html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Ashk3000</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
</head>
<body class="d-flex flex-column" viewport-fit=cover>
<!-- Navbar -->
<script id="navbar_placeholder" src="js/nav.js" page="home"></script>
<!-- Headers -->
<div
class="d-none d-lg-block shadow bg-body border border-5 border-top-0 rounded-bottom w-75 position-relative start-50 translate-middle-x mb-5">
<div class="container-fluid py-5">
<h1 class="display-5 fw-bold">Home</h1>
</div>
</div>
<div class="d-lg-none shadow-sm bg-body border-bottom border-5 w-100 position-relative mb-3">
<div class="container-fluid py-5">
<h1 class="display-5 fw-bold">Home</h1>
</div>
</div>
<!-- Start -->
<div class="container">
<div class="row">
<div id="vid_0"></div>
<div id="vid_1"></div>
<div id="vid_2"></div>
<div class="w-100"></div>
<div id="vid_3"></div>
<div id="vid_4"></div>
<div id="vid_5"></div>
</div>
</div>
<script src="js/videos.js"></script>
<!-- Footer -->
<div class="mt-auto"></div>
<script id="footer_placeholder" src="js/footer.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/js/bootstrap.bundle.min.js"
integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa"
crossorigin="anonymous"></script>
</body>
</html>
videos.html:
<div class="card col" style="width: 18rem;">
<img src="" id="thumbnail" class="card-img-top" alt="">
<div class="card-body">
<h5 id="title" class="card-title">Title</h5>
Watch
</div>
</div>
Hello, I am getting the replit "Not Found" screen when I try this code. I think it has to do with replaceChild. I am new to java script and dont know what it happening. A lot of it is from the internet. I am trying to make it show recent youtube uploads. It wants me to add more text. sorry this is rushed.

When you replace the element, you need to give it the ID of the element that it's replacing, so you will be able to find it the next time.
for (let step = 0; step < 6; step++) {
fetch('js/videos.html')
.then(res => res.text())
.then(text => {
let oldelem = document.getElementById("vid_" + step);
let newelem = document.createElement("div");
newelem.id = oldelem.id; // copy the ID.
newelem.innerHTML = text;
oldelem.parentNode.replaceChild(newelem, oldelem);
var pic = document.getElementById('thumbnail');
pic.classList.add('thumbnail_' + step);
pic.id = "thumbnail_" + step;
pic.setAttribute('src', videos.items[step].snippet.thumbnails.high.url);
})
}
Or instead of replacing the element, you could just update the innerHTML of the old element.
for (let step = 0; step < 6; step++) {
fetch('js/videos.html')
.then(res => res.text())
.then(text => {
let oldelem = document.getElementById("vid_" + step);
oldelem.innerHTML = text;
var pic = document.getElementById('thumbnail');
pic.classList.add('thumbnail_' + step);
pic.id = "thumbnail_" + step;
pic.setAttribute('src', videos.items[step].snippet.thumbnails.high.url);
})
}

Related

how do i make my digital waiting queue management system update to the current token automatically in every device?

(Sorry for poor english, it is not my first language)
The digital queue management i made for a paper needs to be updated manually by every device, i imagine i will need to enter back-end territory so the program is already running in a server, but i'm not well versed in any back-end tecnology and dont know how they can comunicate with the work i have done. my objective is to have the token to update in every machine automaticaly
This is what i managed to do, a friend of mine recomended me the jquery-3.3.1.min package to help
Thank you for your help
<!DOCTYPE html>
<html>
<head>
<title>Queue</title>
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script src="lib/jquery-3.3.1.min.js"></script>
<script src="lib/scripts.js"></script>
</head>
<body>
<div class="barraTop"> </div>
<div class="container page">
<div class="row barraSuperior">
<div class="col-xs-11" style="text-align: right;"><p></p>
<span class="uespiTexto">Waiting queue</span><br>
</div>
</div>
<div class="row">
<div class="senhaAtual">
<div class="row">
<div class="col-xs-5 col-xs-offset-1" style="text-align: right;"><br><br>
<span class="senhaAtualTexto">TOKEN </span>
</div>
<div class="col-xs-5" style="text-align: left;">
<span id="senhaAtualNumero">0000</span>
</div>
<input type="hidden" id="senhaNormal" value="0000">
<input type="hidden" id="senhaPrioridade" value="P000">
</div>
</div>
</div>
<div class="row">
<div class="col-xs-4 col-xs-offset-4 ultimaSenha">
<br>
<span id="ultimaSenhaTexto">LAST TOKEN</span><br>
<span>Token </span>
<span id="ultimaSenhaNumero">0000</span>
</div>
</div>
</div>
<audio id="audioChamada" src="audio/chamada.wav"></audio>
</body>
</html>
let filename = "senhas.txt";
function pad(num, size) {
var s = num+"";
while (s.length < size) s = "0" + s;
return s;
}
jQuery(document).ready(function($) {
$("body").on('keydown', function(e) {
var senhaAtual = $("#senhaAtualNumero");
var senhaNormal = $("#senhaNormal");
var senhaPrior = $("#senhaPrioridade");
var ultimaSenha = $("#ultimaSenhaNumero");
var audioChamada = $("#audioChamada");
if(e.keyCode == 39){
ultimaSenha.html(senhaAtual.html());
senha = parseInt(senhaNormal.val()) + 1;
senhaAtual.html(pad(senha, 4));
senhaNormal.val(pad(senha, 4));
audioChamada.trigger("play");
}
if(e.keyCode == 65){
senha = parseInt(senhaNormal.val()) - 1;
senhaAtual.html(pad(senha, 4));
senhaNormal.val(pad(senha, 4));
}
if(e.keyCode == 38){
ultimaSenha.html(senhaAtual.html());
senha = parseInt(senhaPrior.val().replace("P","")) + 1;
senhaAtual.html("P" + pad(senha, 3));
senhaPrior.val("P" + pad(senha, 3));
audioChamada.trigger("play");
}
if(e.keyCode == 83){
senha = parseInt(senhaPrior.val().replace("P","")) - 1;
senhaAtual.html("P" + pad(senha, 3));
senhaPrior.val("P" + pad(senha, 3));
}
});
});

Multi uploaded video with multi dynamic progress bar

I have <input type="file" multiple /> What I've tried to do is when I select multiple videos, and for each one of them I want:
=> a dynamic progress bar.
=> input field(so the user can change the video name).
=> input type image(default video image).
=> save button (it will be clickable if the user add name value or default image, otherwise will be disabled).
please open this image to see what I mean
what I've tried:
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>File Upload JavaScript with Progress Ba | CodingNepal</title>
<link rel="stylesheet" href="style.css" />
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"
/>
<link rel="shortcut icon" href="#" />
</head>
<body>
<div class="wrapper">
<header>File Uploader</header>
<form action="#">
<input class="file-input" type="file" name="file" hidden multiple />
<i class="fas fa-cloud-upload-alt"></i>
<p>Browse videos to Upload</p>
</form>
<section class="progress-area"></section>
<section class="uploaded-area"></section>
</div>
</body>
<script>
const form = document.querySelector("form"),
fileInput = document.querySelector(".file-input"),
progressArea = document.querySelector(".progress-area"),
uploadedArea = document.querySelector(".uploaded-area");
form.addEventListener("click", () => {
fileInput.click();
});
fileInput.onchange = ({ target }) => {
let files = target.files.length;
for (let i = 0; i < files; i++) {
if (files[i]) {
let fileName = target.files[i]["name"];
if (fileName.length >= 12) {
let splitName = fileName.split(".");
fileName = splitName[0].substring(0, 13) + "... ." + splitName[1];
}
}
let xhr = new XMLHttpRequest();
xhr.open("POST", "php/upload.php");
xhr.upload.addEventListener("progress", ({ loaded, total }) => {
let fileLoaded = Math.floor((loaded / total) * 100);
let fileTotal = Math.floor(total / 1000);
let fileSize;
fileTotal < 1024
? (fileSize = fileTotal + " KB")
: (fileSize = (loaded / (1024 * 1024)).toFixed(2) + " MB");
let progressHTML = `
<li class="row">
<i class="fas fa-file-alt"></i>
<div class="content">
<div class="details">
<span class="name">${target.files[i]["name"]} • Uploading</span>
<span class="percent">${fileLoaded}%</span>
</div>
<div class="progress-bar">
<div class="progress" style="width: ${fileLoaded}%"></div>
</div>
</div>
</li>
`;
uploadedArea.classList.add("onprogress");
progressArea.innerHTML = progressHTML;
if (loaded === total) {
progressArea.innerHTML = "";
let uploadedHTML = `
<li class="row">
<div class="content upload">
<i class="fas fa-file-alt"></i>
<div class="details">
<span class="name">${target.files[i]["name"]} • Uploaded</span>
<span class="size">${fileSize}</span>
</div>
</div>
<i class="fas fa-check"></i>
</li>
`;
uploadedArea.classList.remove("onprogress");
uploadedArea.insertAdjacentHTML("afterbegin", uploadedHTML);
}
});
let data = new FormData(form);
xhr.send(data);
}
};
</script>
</html>
upload.php
<?php
if (isset($_FILES['files'])) {
for ($count = 0; $count < count($_FILES['files']['name']); $count++) {
$extension = pathinfo($_FILES['files']['name'][$count], PATHINFO_EXTENSION);
$new_name = uniqid() . '.' . $extension;
move_uploaded_file($_FILES['files']['tmp_name'][$count], 'files/' . $new_name);
}
echo 'success';
}
So, in the controller To get the videos,
function getVideos(Request $request){
$request->all();
return true;
}
The problem is he just gives one progress bar!

How do i fix the result without reloading the site?

Whenever I am writing apple or samsung, It is showing results, but if I don't refresh the page for the second time, it gives me error. However, If I reload the website, then it is showing me the results of samsung or oppo or whatever. Can you please tell me where I made the mistake ? I am attaching the HTML and JS below :
// error handle
const displayHandle = (direction, id) => {
const errorMessage = document.getElementById(id);
errorMessage.style.display = direction;
}
// clear previous result
const clearSearchResult = (direction) => {
const searchResult = document.getElementById(direction);
searchResult.innerHTML = '';
}
// details button action form
const allDetails = (id) => {
// console.log(id)
fetch(`https://openapi.programming-hero.com/api/phone/${id}`)
.then(response => response.json())
.then(data => {
const sensorName = data.data.mainFeatures.sensors;
let storeSensorName = '';
for (const sensor of sensorName) {
storeSensorName = `${storeSensorName} ${sensor}, `
}
const mobileDetails = document.getElementById('show-details');
mobileDetails.innerHTML = `
<div class=" row row-cols-1 row-cols-md-3 g-4">
<div class="col">
<div class="card">
<img src=${data.data.image} class="card-img-top w-50 h-50" alt="...">
<div id="details-body" class="card-body">
<h5 class="card-title">Brand: ${data.data.brand}</h5>
<p class="card-text">Storage: ${data.data.mainFeatures.storage}</p>
<p class="card-text">ChipSet: ${data.data.mainFeatures.chipSet}</p>
<p class="card-text">DisplaySize: ${data.data.mainFeatures.displaySize}</p>
<p class="card-text">Sensors : ${storeSensorName}</p>
</div>
</div>
</div>
</div>
`;
// inject release Date
const container = document.getElementById('details-body');
const p = document.createElement('p');
if (data.data.releaseDate) {
p.innerText = `Release Information:${data.data.releaseDate}`;
container.appendChild(p);
} else {
p.innerText = `Release Information Not Found`;
container.appendChild(p);
}
});
}
//search button action form
document.getElementById('search-btn').addEventListener('click', function() {
clearSearchResult('show-details');
clearSearchResult('show-mobile');
displayHandle('none', 'error-message');
displayHandle('none', 'show-all-Button')
// get search field
const searchBox = document.getElementById('search-box');
const searchData = searchBox.value;
fetch(`https://openapi.programming-hero.com/api/phones?search=${searchData}`)
.then(res => res.json())
.then(data => {
if (data.data.length != 0) {
displayMobile(data.data)
} else {
displayHandle('block', 'error-message');
}
})
// clear search field
searchBox.value = ' ';
})
const displayMobile = (mobiles) => {
// console.log(phones);
const showMobile = document.getElementById('show-mobile');
let count = 0;
for (const mobile of mobiles) {
if (count < 20) {
const div = document.createElement('div');
div.classList.add("col");
div.innerHTML = `
<div class="card d-flex align-items-center">
<img src=${mobile.image} class="card-img-top w-50 h-50" alt="...">
<div class="card-body">
<h5 class="card-title">Model : ${mobile.phone_name}</h5>
<p class="card-text">Brand : ${mobile.brand}</p>
<button class="card-button" onclick="allDetails('${mobile.slug}')">Details</button>
</div>
</div>
`;
showMobile.appendChild(div);
} else {
displayHandle('block', 'show-all-Button');
}
count++;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- connection with bootstrap -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<style>
.display-handle {
display: none;
color: rgb(231, 49, 49);
}
.card-button {
color: white;
background-color: brown;
border-radius: 10px;
}
</style>
</head>
<body>
<!-- search box section
----------------->
<section class="container w-75 mx-auto pt-5">
<h5 id="error-message" class="display-handle text-center">Not found..! Press authentic data...</h5>
<h3 class="text-center bg-dark text-white">Mobile Maya</h3>
<div class="input-group mb-3">
<input id="search-box" type="text" class="form-control" placeholder="Enter your desired mobile " aria-label="" aria-describedby="button-addon2">
<button class="btn btn-success" type="button" id="search-btn">Search</button>
</div>
</section>
<!-- display products details -->
<section id="show-details" class="container">
<!-- inject details here -->
</section>
<!-- search result display section
---------------------------------->
<section class="container pt-5">
<div id="show-mobile" class=" row row-cols-1 row-cols-md-3 g-4">
</div>
</section>
<!-- show all button -->
<section class="container">
<div class="d-flex justify-content-center">
<button style="color: white; background-color:tomato; border-radius: 8px;" id="show-all-Button" class="display-handle" type="button" class="btn btn-primary">Show All</button>
</div>
</section>
<!-- connection with js
----------- -->
<script src="js/app.js"></script>
<!-- connection with bootstrap script -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</body>
</html>
It is because of this line, you don't really clear the search field :
// clear search field
searchBox.value = ' ';
You should either assign the empty string value '' or call the method trim() on searchData.

Remove already added class when value it different

This is a simple issue that I am having. I am new to javascript and trying to create a BMI calculator with a color code to indicate the BMI result. I am adding a class to the color based on the BMI result. for eg. I am adding "active" class to the "normal" div when the BMI is normal. Same for others. But if a class is added I can not remove it when other is selected.
How can I fix it?
const hFeet = document.querySelector("#hFeet");
const hInch = document.querySelector("#hInch");
const wKg = document.querySelector("#wKg");
const submit = document.querySelector("#submit");
const result = document.querySelector("#result_area");
const wStatus = document.querySelector("#wst");
submit.addEventListener("click", bmiFunc);
function bmiFunc(event) {
event.preventDefault();
const height = hFeet.value * 0.3048 + hInch.value * 0.0254;
const weight = wKg.value;
const calculation = weight / Math.pow(height, 2);
const final = calculation.toFixed(2);
result.innerHTML = final;
if (final < 16) {
wStatus.innerHTML = "Severe Thinness";
document.querySelector(".thin1").classList.add("active");
} else if (final >= 16 && final < 17) {
wStatus.innerHTML = "Moderate Thinness";
document.querySelector(".thin2").classList.add("active");
} else if (final >= 17 && final < 18.5) {
wStatus.innerHTML = "Mild Thinness";
document.querySelector(".thin3").classList.add("active");
} else if (final > 18.5 && final <= 25) {
wStatus.innerHTML = "Normal";
document.querySelector(".norm1").classList.add("active");
} else if (final > 25 && final <= 30) {
wStatus.innerHTML = "Overweight";
document.querySelector(".ow1").classList.add("active");
} else if (final > 30 && final <= 35) {
wStatus.innerHTML = "Obese Class I";
document.querySelector(".obs1").classList.add("active");
} else if (final >= 35 && final <= 40) {
wStatus.innerHTML = "Mild Thinness";
document.querySelector(".obs2").classList.add("active");
} else if (final > 40) {
wStatus.innerHTML = "Mild Thinness";
document.querySelector(".obs3").classList.add("active");
}
}
.color .column {
height: 30px;
transition: all 0.2s ease-in;
}
.clm_thin .thin1 {
background: #ff9595;
}
.clm_thin .thin2 {
background: #ffafaf;
}
.clm_thin .thin3 {
background: #ffdab6;
}
.clm_normal .norm1 {
background: #4e9b00;
}
.clm_overWeight .ow1 {
background: #f5f500;
}
.clm_obesity .obs1 {
background: #ff7474;
}
.clm_obesity .obs2 {
background: #ff3e3e;
}
.clm_obesity .obs3 {
background: #db0000;
}
.active {
transform: scale(1.5);
}
.bmi_scale {
margin-top: 30px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- Google Fonts -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,300italic,700,700italic" />
<!-- CSS Reset -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.css" />
<!-- Milligram CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/milligram/1.4.1/milligram.css" />
<!-- You should properly set the path from the main file. -->
<link rel="stylesheet" href="assets/css/style.css" />
<title>BMI calculator</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="column">
<div class="bmi_wrapper">
<div class="bmi_form">
<form action="">
<div class="bmi_height">
<h3>Your Height:</h3>
<div class="row">
<div class="column">
<input type="text" name="hFeet" id="hFeet" />
<label for="hFeet">feet</label>
</div>
<div class="column">
<input type="text" name="hInch" id="hInch" />
<label for="hInch">inchs</label>
</div>
</div>
</div>
<!-- bmi_height -->
<div class="bmi_weight">
<h3>Your weight:</h3>
<div class="row">
<div class="column">
<input type="text" name="wKg" id="wKg" />
<label for="wKg">Kg</label>
</div>
</div>
</div>
<!-- bmi_weight -->
<div class="bmi_btn">
<input type="submit" value="Calculate BMI" id="submit" />
</div>
<!-- bmi_btn -->
</form>
</div>
<!-- bmi_form -->
<div class="bmi_result">
<div class="bmi">Your BMI is: <span id="result_area">0</span> kg/m<sup>2</sup></div>
<div class="wStatus">Weight Status: <span id="wst"></span></div>
</div>
<!-- bmi_result -->
<div class="bmi_scale">
<div class="row">
<div class="column clm_thin">
<div class="row color">
<div class="column thin1 column-50"></div>
<div class="column thin2 column-25"></div>
<div class="column thin3 column-25"></div>
</div>
</div>
<!-- column_thin -->
<div class="column clm_normal">
<div class="row color">
<div class="column norm1"></div>
</div>
</div>
<!-- column_normal -->
<div class="column clm_overWeight">
<div class="row color">
<div class="column ow1"></div>
</div>
</div>
<div class="column clm_obesity">
<div class="row color">
<div class="column obs1"></div>
<div class="column obs2"></div>
<div class="column obs3"></div>
</div>
</div>
</div>
</div>
<!-- bmi_scale -->
</div>
<!-- bmi_wrapper -->
</div>
<!-- column -->
</div>
<!-- row -->
</div>
<!-- container -->
</body>
</html>
Here is the jsfiddle link
jsfiddle
The simplest you can do is reset beforehand the class from your ".active":
In the lack of a more descriptive className - use .bmi_scale .column to target the "columns"
document.querySelector(".bmi_scale .column.active").classList.remove("active");
// if (final < 16) { etc.....
Or, if needed for some case - from all:
document.querySelectorAll(".bmi_scale .column").forEach(el => {
el.classList.remove("active")
});
// if (final < 16) { etc.....

Building calculator - Not getting it to work

I'm building a calculator, and while it's starting to work, I'm kind of stuck. I've pasted the HTML and the JS down here.
I've been trying to figure out what went wrong, and I think it's because of the functions calling each other and not properly... "closing/ending". I've been trying to see what went wrong with adding console.logs. I'll break it down here:
I press "on" and function listenFirst gets run.
listenFirst has an eventListener and waits for the user to click a number (firstNumber). As soon as a number is clicked, waitforOperator is run (which now has the firstNumberas an attribute. Now,
waitforOperator waits for a click on the plus sign, and as soon as the user clicks on the plus sign, listenSecondgets run. Now this is where it
goes wrong: as soon as I click the second number, waitforOperatorgets run again and now firstNumber and secondNumber are the same.
To be clear: I just want this problem solved before I delve into the other operators, so please don't pay attention to the other operators like minus and multiplication.
A nudge in the right direction would be nice! Thanks in advance.
let displayBox = document.getElementById("displayBox");
let pressButton = document.querySelectorAll(".column");
let turnOn = document.getElementById("turnOn");
let minus = document.getElementById("minus");
let plus = document.getElementById("plus");
let firstNumber = Number();
let secondNumber = Number();
turnOn.addEventListener("click", function() {
displayBox.textContent = "CALCULATOR ON. GIVE FIRST NR.";
console.log("launching function listenFirst");
listenFirst();
});
let listenFirst = () => {
console.log("launched listenFirst");
for (var i = 0; i < pressButton.length; i++) {
pressButton[i].addEventListener("click", function() {
firstNumber = displayBox.textContent = Number(this.id);
waitForOperator(firstNumber);
});
}
};
let listenSecond = () => {
console.log("launched listenSecond");
console.log(`first number is still ${firstNumber}`)
console.log(`waiting for you to press second number`)
for (var i = 0; i < pressButton.length; i++) {
pressButton[i].addEventListener("click", function() {
secondNumber = displayBox.textContent = Number(this.id);
console.log(`After click on second number, first number is ${firstNumber} and second number is ${secondNumber}`)
});
}
console.log(
`Now first number is ${firstNumber} and second number is ${secondNumber}`
);
};
let waitForOperator = () => {
console.log("launched waitForOperator");
console.log(`First number is ${firstNumber}`);
console.log("Waiting for you to press plus");
plus.addEventListener("click", function() {
listenSecond(firstNumber);
});
};
let calculateSum = () => {
console.log(`Second number is ${secondNumber}`);
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Hello Bulma!</title>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.2/css/bulma.min.css"
/>
<script
defer
src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"
></script>
<link rel="stylesheet" href="index.css" />
</head>
<body>
<section class="section">
<h1 class="title has-text-centered" id="titleText">Calculator.</h1>
<div class="container">
<div class="field">
<a class="button is-fullwidth is-static" id="displayBox"></a><a class="button is-success" id="turnOn">ON</a>
</div>
<div class="calculator">
<div class="columns">
<div class="column" id="7">7</div>
<div class="column" id="8">8</div>
<div class="column" id="9">9</div>
<div class="column" id="minus">-</div>
</div>
<div class="columns">
<div class="column" id="4">4</div>
<div class="column" id="5">5</div>
<div class="column" id="6">6</div>
<div id="plus">+</div>
</div>
<div class="columns">
<div class="column" id="1">1</div>
<div class="column" id="2">2</div>
<div class="column" id="3">3</div>
<div class="column" id="equals">=</div>
</div>
<div class="columns">
<div class="column" id="0">0</div>
<div class="column" id="dot">.</div>
</div>
</div>
</div>
</section>
<script src="script.js"></script>
</body>
</html>
You never remove the event listener you added to number number buttons in listenFirst. So when the user presses the buttons after waitForOperator both the code in listenFirst and listenSecond runs. listenFirst call waitForOperator again.
JavaScript: remove event listener Have a look at this answer for how to remove event listeners.

Categories