I've added a back button to my calculator with the idea that when someone presses it they can undo if they clicked the wrong number.
I've tried to solve using substr within an if statement in my calculate function but nothing seems to be happening it's as if it's not recording when the user clicks the button. To be honest I'm not sure this is the correct approach!
//Create variable to hold display value, create variable of display area and populate.
let toShow = 0;
let displayValue = 0;
let displayArea = document.getElementById('result-display');
let dataType = document.querySelectorAll('[data-type]');
let operator = "";
let firstNumber = 0;
let secondNumber = 0;
let operatorPressed = false;
let secondNumberCounter = false;
let firstNumberCounter = false;
let buttonNumber = 0;
let decimalCounter = 0;
displayArea.innerHTML = 0;
/* displayArea.innerHTML += displayValue; */
//Basic math functions
add = (firstNumber, secondNumber) => firstNumber + secondNumber;
subtract = (firstNumber, secondNumber) => firstNumber - secondNumber;
multiply = (firstNumber, secondNumber) => firstNumber * secondNumber;
divide = (firstNumber, secondNumber) => firstNumber / secondNumber;
//Take an operator and two numbers and call a math function
operate = (operator, firstNumber, secondNumber) => {
toShow = operator(firstNumber, secondNumber);
return Math.round(toShow * 100) / 100;
};
//Update display with button clicked
const button = document.querySelectorAll('.item');
addEventListener('click', e => {
calculate(e);
});
let calculate = (e) => {
if (e.target.id === "equals" && secondNumber === 0) {
displayArea.innerHTML = "OH HELL NO!";
} else if (e.target.id === "equals") {
decimalCounter = 0;
switch (operator) {
case "add":
secondNumberCounter = false;
return firstNumber = displayArea.innerHTML = operate(add, firstNumber, secondNumber);
case "multiply":
secondNumberCounter = false;
return firstNumber = displayArea.innerHTML = operate(multiply, firstNumber, secondNumber);
case "divide":
secondNumberCounter = false;
return firstNumber = displayArea.innerHTML = operate(divide, firstNumber, secondNumber);
case "subtract":
secondNumberCounter = false;
return firstNumber = displayArea.innerHTML = operate(subtract, firstNumber, secondNumber);
}
}
if (operatorPressed === true && e.target.dataset.type === "number") {
if (secondNumberCounter === false) {
displayArea.innerHTML = null;
}
if (decimalCounter === 0) {
let secondButtonNumber = e.target.innerText;
displayValue = secondButtonNumber;
displayArea.innerHTML += displayValue;
secondNumber = Number(displayArea.innerHTML);
secondNumberCounter = true;
}
} else if (e.target.dataset.type === "nonNumber") {
decimalCounter = 0;
operator = e.target.id;
firstNumber = Number(displayArea.innerText);
operatorPressed = true;
} else {
if (e.target.id === "decimal" && decimalCounter === 0) {
++decimalCounter;
buttonNumber = e.target.innerText;
displayValue = buttonNumber;
displayArea.innerHTML += displayValue;
console.log(buttonNumber);
} else {
buttonNumber = Number(e.target.innerText);
displayValue = buttonNumber;
displayArea.innerHTML += displayValue;
displayArea.innerHTML = Number(displayArea.innerHTML);
}
}
if (e.target.id === "AC") {
secondNumberCounter = false;
operatorPressed = false;
firstNumber = 0;
secondNumber = 0;
buttonNumber = 0;
decimalCounter = 0;
displayArea.innerHTML = 0;
}
}
body {
display: flex;
align-items: center;
justify-content: center;
border: 1px solid black;
flex-direction: row;
width: 100%;
height: 100vh;
}
.container {
display: flex;
align-items: center;
justify-content: center;
background-color: gray;
width: 275px;
height: 450px;
border: 1px solid black;
}
.sub-container {
display: flex;
flex-direction: column;
align-items: center;
height: 95%;
width: 800%;
}
.display {
display: flex;
align-items: center;
justify-content: flex-end;
border: 1px solid white;
width: 80%;
height: 10%;
margin: 5% 0 5% 0;
color: white;
}
#result-display {
margin-right: 8%;
}
.button-grid {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
height: 100%;
width: 80%;
}
.item {
width: 50px;
height: 50px;
border: 1px solid white;
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
color: black;
}
button {
width: 100%;
height: 100%;
}
footer {
width: 100%;
background-color: gray;
}
Make the calculator work! You’ll need to store the first number that is input into the calculator when a user presses an operator,
and also save which operation has been chosen and then operate() on them when the user presses the “=” key.
<div class="container">
<div class="sub-container">
<div class="display">
<p id="result-display">
</p>
</div>
<div class="button-grid">
<div>
<button class="item" id="7" data-type="number">
7
</button>
</div>
<div>
<button class="item" id="8" data-type="number">
8
</button>
</div>
<div>
<button class="item" id="9" data-type="number">
9
</button>
</div>
<div>
<button class="item" id="divide" data-type="nonNumber">
*/*
</button>
</div>
<div>
<button class="item" id="4" data-type="number">
4
</button>
</div>
<div>
<button class="item" id="5" data-type="number">
5
</button>
</div>
<div>
<button class="item" id="6" data-type="number">
6
</button>
</div>
<div>
<button class="item" id="multiply" data-type="nonNumber">
X
</button>
</div>
<div>
<button class="item" id="1" data-type="number">
1
</button>
</div>
<div>
<button class="item" id="2" data-type="number">
2
</button>
</div>
<div>
<button class="item" id="3" data-type="number">
3
</button>
</div>
<div>
<button class="item" id="subtract" data-type="nonNumber">
-
</button>
</div>
<div>
<button class="item" id="0" data-type="number">
0
</button>
</div>
<div>
<button class="item" id="decimal" data-type="number">
.
</button>
</div>
<div>
<button class="item" id="AC" data-type="nonNumber">
AC
</button>
</div>
<div>
<button class="item" id="add" data-type="nonNumber">
+
</button>
</div>
<div>
<button class="item" id="equals" data-type="nonNumber">
=
</button>
</div>
<div>
<button class="item" id="back" data-type="nonNumber">
<
</button>
</div>
</div>
</div>
</div>
<div>
<!-- User presses back button
preprend displayValue
displayValue remove one
displayArea.innerHTML remove one
let str = 'Mozilla';
let smallStr = str.substr(0, str.length - 1);-->
You can use either The Memento Pattern or The Command Pattern explained here:
How to make a undo/redo function
I ended up solving this using substring. Basically I look for the length of the string in my calculators display then remove the last character.
Code used in an IF Statement:
if (e.target.id === "back") {
displayArea.innerHTML = displayArea.innerHTML.substring(0, displayArea.innerHTML.length - 1);
}
Related
I am creating a calculator app using HTML, CSS, and JS as my stack.
When the user attempts to inputs a number, the behavior of the calculator is fine with single-digit arithmetic. However, as soon as the user attempts to input any number longer than two digits, the calculator drops all of the digits except for the first of both numbers and then proceeds to execute the arithmetic.
// Initializing all variables
const currentDisplay = document.querySelector(".current");
const previousDisplay = document.querySelector(".previous");
const numberButtons = document.querySelectorAll('[data-number]');
const operationButtons = document.querySelectorAll('[data-operation]');
const clearButton = document.querySelector(".clear");
const deleteButton = document.querySelector(".delete");
const enterButton = document.querySelector(".enter");
const pointButton = document.querySelector(".point");
let firstNumber;
let secondNumber;
let operand;
let answer;
// Adding event listeners to all buttons
clearButton.addEventListener('click', clearAll);
enterButton.addEventListener('click', enter);
numberButtons.forEach(button =>
button.addEventListener('click', () => {
/*
Checks if firstNumber is assigned yet.
If firstNumber & operand is undefined, just assign value of button to firstNumber.
If firstNumber has a value assigned and the operand is undefined, that means they pressed a number button already, append and reassign to firstNumber.
If secondNumber and operand is defined, then we know the user is appending to the secondNumber
Else they are just beginning to type their secondNumber.
*/
if (isUndefined(firstNumber) && isUndefined(operand)) {
firstNumber = parseFloat(button.textContent);
currentDisplay.textContent = firstNumber;
console.log("Case 1: firstNumber: " + firstNumber);
} else if (!isUndefined(firstNumber) && isUndefined(operand)) {
appendToCurrent(button.textContent);
firstNumber = parseFloat(currentDisplay.textContent);
console.log("Case 2: firstNumber: " + firstNumber);
} else if (!isUndefined(secondNumber) && !isUndefined(operand)) {
appendToCurrent(button.textContent);
secondNumber = parseFloat(currentDisplay.textContent);
console.log("Case 1: secondNumber: " + secondNumber);
} else {
secondNumber = parseFloat(button.textContent);
currentDisplay.textContent = secondNumber;
console.log("Case 2: secondNumber: " + secondNumber);
}
}));
operationButtons.forEach(button =>
button.addEventListener('click', () => {
/*
Checks if there is the operand & firstNumber has been assigned yet.
If both the operand and firstNumber is undefined, then they are trying to do some sort of arithemtic with zero (aka the starting value).
If the operand is undefined but the firstNumber isn't, that means the user has finished inputting their number and are moving onto an arithmetic operation.
*/
if (isUndefined(operand) && !isUndefined(firstNumber)) {
operand = button.textContent;
appendToPrevious(button.textContent);
}
if (isUndefined(operand) && isUndefined(firstNumber)) {
operand = button.textContent;
appendToPrevious(button.textContent);
}
}));
function appendToCurrent(number) {
currentDisplay.textContent += number
}
function appendToPrevious(op) {
/*
Takes in a button (which contains the operand) and assigns it to the 'operand' variable. Moves currentDisplay to previousDisplay while appending the operand to it. Afterwards, clear the currentDisplay readying it for new user input.
*/
previousDisplay.textContent = currentDisplay.textContent;
previousDisplay.textContent += op;
clear(currentDisplay);
}
function isUndefined(variable) {
return variable === undefined;
}
function del() {
}
function enter() {
console.log(operand + (typeof operand));
switch (operand.trim()) {
case "+":
console.log("Case: Addition");
answer = add(firstNumber, secondNumber);
previousDisplay.textContent = firstNumber + operand + secondNumber;
currentDisplay.textContent = answer;
break;
case "-":
console.log("Case: Subtraction");
previousDisplay.textContent = firstNumber + operand + secondNumber;
answer = subtract(firstNumber, secondNumber);
currentDisplay.textContent = answer;
break;
case "/":
console.log("Case: Division");
previousDisplay.textContent = firstNumber + operand + secondNumber;
answer = divide(firstNumber, secondNumber);
currentDisplay.textContent = answer;
break;
case "*":
console.log("Case: Multiplication");
previousDisplay.textContent = firstNumber + operand + secondNumber;
answer = multiply(firstNumber, secondNumber);
currentDisplay.textContent = answer;
break;
default:
console.log("Case: Default");
previousDisplay.textContent = firstNumber + operand + secondNumber;
break;
}
}
function clearAll() {
currentDisplay.textContent = 0;
previousDisplay.textContent = ' ';
firstNumber = undefined;
secondNumber = undefined;
operand = undefined;
console.clear();
}
function clear(display) {
display.textContent = ' ';
}
function add(x, y) {
return x + y;
}
function subtract(x, y) {
return x - y;
}
function multiply(x, y) {
return x * y;
}
function divide (x, y) {
return x / y;
}
/* #EEC61F */
* {
padding: 0;
margin: 0;
font-family: 'Fira Code';
}
head {
display: none;
}
body {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: lightgray;
}
/* Main app */
.app {
display: flex;
align-items: center;
justify-content: center;
height: 500px;
padding: 20px;
}
.calculator {
width: 400px;
border: 2px solid black;
border-radius: 10px;
padding: 20px;
background-color: gray;
}
.display {
background-color: whitesmoke;
text-align: right;
word-break: break-all;
padding: 10px 20px;
margin-bottom: 30px;
border: 1.5px solid black;
border-radius: 10px;
}
.current {
padding: 10px;
font-size: 2em;
}
.previous {
padding: 10px;
font-size: 1em;
}
.buttons {
display: grid;
grid-template-columns: repeat(4, 2fr);
gap: 20px;
}
#button {
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
border: 1px solid black;
border-radius: 3px;
background-color: whitesmoke;
}
.zero {
grid-column-start: 1;
grid-column-end: 3;
grid-row-start: 5;
grid-row-end: 5;
}
.enter {
grid-column-start: 4;
grid-column-end: 4;
grid-row-start: 4;
grid-row-end: 6;
}
<!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">
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="https://fonts.google.com/specimen/Fira+Code?vfquery=fira">
<script src="script.js" defer></script>
<title>Calculator</title>
</head>
<body>
<div class="app">
<div class="calculator">
<div class="display">
<div class="previous"></div>
<div class="current">0</div>
</div>
<div class="buttons">
<button id="button" class="clear">
<h3> CLEAR </h3>
</button>
<button id="button" data-operation>
<h3> / </h3>
</button>
<button id="button" data-operation>
<h3> * </h3>
</button>
<button id="button" class="delete">
<h3> ⌫ </h3>
</button>
<button id="button" data-number>
<h3> 7 </h3>
</button>
<button id="button" data-number>
<h3> 8 </h3>
</button>
<button id="button" data-number>
<h3> 9 </h3>
</button>
<button id="button" data-operation="">
<h3> - </h3>
</button>
<button id="button" data-number>
<h3> 4 </h3>
</button>
<button id="button" data-number>
<h3> 5 </h3>
</button>
<button id="button" data-number>
<h3> 6 </h3>
</button>
<button id="button" data-operation>
<h3> + </h3>
</button>
<button id="button" data-number>
<h3> 1 </h3>
</button>
<button id="button" data-number>
<h3> 2 </h2>
</button>
<button id="button" data-number>
<h3> 3 </h3>
</button>
<button id="button" class="enter">
<h3> ENTER </h3>
</button>
<button id="button" class="zero" data-number>
<h3> 0 </h3>
</button>
<button id="button" class="point">
<h3> . </h3>
</button>
</div>
</div>
</div>
</body>
</html>
Your issue appears to be in the appendToCurrent() function. You need to trim the number parameter before you add it to the current number:
function appendToCurrent(number)
{
const newNumber = currentDisplay.textContent += number.trim()
return newNumber
}
// Initializing all variables
const currentDisplay = document.querySelector(".current");
const previousDisplay = document.querySelector(".previous");
const numberButtons = document.querySelectorAll('[data-number]');
const operationButtons = document.querySelectorAll('[data-operation]');
const clearButton = document.querySelector(".clear");
const deleteButton = document.querySelector(".delete");
const enterButton = document.querySelector(".enter");
const pointButton = document.querySelector(".point");
let firstNumber;
let secondNumber;
let operand;
let answer;
// Adding event listeners to all buttons
clearButton.addEventListener('click', clearAll);
enterButton.addEventListener('click', enter);
numberButtons.forEach(button =>
{
button.addEventListener('click', () =>
{
/*
Checks if firstNumber is assigned yet.
If firstNumber & operand is undefined, just assign value of button to firstNumber.
If firstNumber has a value assigned and the operand is undefined, that means they pressed a number button already, append and reassign to firstNumber.
If secondNumber and operand is defined, then we know the user is appending to the secondNumber
Else they are just beginning to type their secondNumber.
*/
if (isUndefined(firstNumber) && isUndefined(operand))
{
firstNumber = parseFloat(button.textContent);
currentDisplay.textContent = firstNumber;
}
else if (!isUndefined(firstNumber) && isUndefined(operand))
{
appendToCurrent(button.textContent);
firstNumber = parseFloat(currentDisplay.textContent);
}
else if (!isUndefined(secondNumber) && !isUndefined(operand))
{
appendToCurrent(button.textContent);
secondNumber = parseFloat(currentDisplay.textContent);
}
else
{
secondNumber = parseFloat(button.textContent);
currentDisplay.textContent = secondNumber;
}
})
})
operationButtons.forEach(button =>
button.addEventListener('click', () => {
/*
Checks if there is the operand & firstNumber has been assigned yet.
If both the operand and firstNumber is undefined, then they are trying to do some sort of arithemtic with zero (aka the starting value).
If the operand is undefined but the firstNumber isn't, that means the user has finished inputting their number and are moving onto an arithmetic operation.
*/
if (isUndefined(operand) && !isUndefined(firstNumber)) {
operand = button.textContent;
appendToPrevious(button.textContent);
}
if (isUndefined(operand) && isUndefined(firstNumber)) {
operand = button.textContent;
appendToPrevious(button.textContent);
}
}));
function appendToCurrent(number)
{
const newNumber = currentDisplay.textContent += number.trim()
return newNumber
}
function appendToPrevious(op) {
/*
Takes in a button (which contains the operand) and assigns it to the 'operand' variable. Moves currentDisplay to previousDisplay while appending the operand to it. Afterwards, clear the currentDisplay readying it for new user input.
*/
previousDisplay.textContent = currentDisplay.textContent;
previousDisplay.textContent += op;
clear(currentDisplay);
}
function isUndefined(variable) {
return variable === undefined;
}
function del() {
}
function enter() {
switch (operand.trim()) {
case "+":
answer = add(firstNumber, secondNumber);
previousDisplay.textContent = firstNumber + operand + secondNumber;
currentDisplay.textContent = answer;
break;
case "-":
previousDisplay.textContent = firstNumber + operand + secondNumber;
answer = subtract(firstNumber, secondNumber);
currentDisplay.textContent = answer;
break;
case "/":
previousDisplay.textContent = firstNumber + operand + secondNumber;
answer = divide(firstNumber, secondNumber);
currentDisplay.textContent = answer;
break;
case "*":
previousDisplay.textContent = firstNumber + operand + secondNumber;
answer = multiply(firstNumber, secondNumber);
currentDisplay.textContent = answer;
break;
default:
previousDisplay.textContent = firstNumber + operand + secondNumber;
break;
}
}
function clearAll() {
currentDisplay.textContent = 0;
previousDisplay.textContent = ' ';
firstNumber = undefined;
secondNumber = undefined;
operand = undefined;
console.clear();
}
function clear(display) {
display.textContent = ' ';
}
function add(x, y) {
return x + y;
}
function subtract(x, y) {
return x - y;
}
function multiply(x, y) {
return x * y;
}
function divide(x, y) {
return x / y;
}
/* #EEC61F */
* {
padding: 0;
margin: 0;
font-family: 'Fira Code';
}
head {
display: none;
}
body {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: lightgray;
}
/* Main app */
.app {
display: flex;
align-items: center;
justify-content: center;
height: 500px;
padding: 20px;
}
.calculator {
width: 400px;
border: 2px solid black;
border-radius: 10px;
padding: 20px;
background-color: gray;
}
.display {
background-color: whitesmoke;
text-align: right;
word-break: break-all;
padding: 10px 20px;
margin-bottom: 30px;
border: 1.5px solid black;
border-radius: 10px;
}
.current {
padding: 10px;
font-size: 2em;
}
.previous {
padding: 10px;
font-size: 1em;
}
.buttons {
display: grid;
grid-template-columns: repeat(4, 2fr);
gap: 20px;
}
#button {
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
border: 1px solid black;
border-radius: 3px;
background-color: whitesmoke;
}
.zero {
grid-column-start: 1;
grid-column-end: 3;
grid-row-start: 5;
grid-row-end: 5;
}
.enter {
grid-column-start: 4;
grid-column-end: 4;
grid-row-start: 4;
grid-row-end: 6;
}
<div class="app">
<div class="calculator">
<div class="display">
<div class="previous"></div>
<div class="current">0</div>
</div>
<div class="buttons">
<button id="button" class="clear">
<h3> CLEAR </h3>
</button>
<button id="button" data-operation>
<h3> / </h3>
</button>
<button id="button" data-operation>
<h3> * </h3>
</button>
<button id="button" class="delete">
<h3> ⌫ </h3>
</button>
<button id="button" data-number>
<h3> 7 </h3>
</button>
<button id="button" data-number>
<h3> 8 </h3>
</button>
<button id="button" data-number>
<h3> 9 </h3>
</button>
<button id="button" data-operation="">
<h3> - </h3>
</button>
<button id="button" data-number>
<h3> 4 </h3>
</button>
<button id="button" data-number>
<h3> 5 </h3>
</button>
<button id="button" data-number>
<h3> 6 </h3>
</button>
<button id="button" data-operation>
<h3> + </h3>
</button>
<button id="button" data-number>
<h3> 1 </h3>
</button>
<button id="button" data-number>
<h3> 2 </h2>
</button>
<button id="button" data-number>
<h3> 3 </h3>
</button>
<button id="button" class="enter">
<h3> ENTER </h3>
</button>
<button id="button" class="zero" data-number>
<h3> 0 </h3>
</button>
<button id="button" class="point">
<h3> . </h3>
</button>
</div>
</div>
</div>
I want to create a to do list that will add elements typed in <input type="text"> and delete when clicked on button with class .delete. When ever I push elements in an array. And innerHTML it in html page, the delete button stops working. The delete button works for elements that are written into Html code. If someone can help me I will be very thankful.
`
const itemsLIst = document.querySelector('.item-list'); // where we want to add our list
const addText = document.querySelector('.submit'); // add button
let deleteText = document.querySelectorAll('.delete'); // delete button
// const list = JSON.parse(localStorage.getItem('items')) || [];
let list = [];
function addItem(e) {
let text = document.querySelector('.input_bar').value; //text typed in input bar
if (text.length != 0) {
list.push(`<div>
<p>${text}</p>
<button class="delete" onclick='deleteItem'>🗴</button>
<button class="edit">Edit</button>
</div><hr>`);
itemsLIst.innerHTML = list.join('');
text = '0';
document.getElementById("myText").value = "";
} else {
return;
}
}
function deleteItem(e) {
this.parentElement.style.display = 'none';
}
for (var i = 0 ; i < deleteText.length; i++) {
deleteText[i].addEventListener('click', deleteItem);
}
addText.addEventListener('click', addItem);
<style>
body {
width: 100%;
height: 100vh;
background-color: rgb(115, 115, 197);
margin: 0;
padding: 0;
position: relative;
}
.container {
width:50%;
height:70%;
position: absolute;
background-color: rgb(241, 241, 241);
font-family: Arial, Helvetica, sans-serif;
border-bottom-left-radius: 25px;
border-bottom-right-radius: 25px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
overflow-y: scroll;
}
.heading {
width: 100%;
height: 122px;
background-color: #5B45B9;
display: flex;
align-items: center;
justify-content: center;
}
.heading h1 {
color: white;
font-size: 40px;
}
.item-list {
width: 100%;
padding: 0 0 30px 0;
}
.item-list div {
width: auto;
height: 60px;
}
p {
width: 60%;
float: left;
font-size: 25px;
padding-left: 30px;
margin-top: 12px ;
}
.item-list button {
width: 60px;
height: 60px;
font-size: 18px;
float: right;
}
.delete {
font-size: 30px;
color: red;
}
.input_form {
width: 100%;
padding: 30px 0 30px 0;
position: absolute;
bottom: 0;
text-align: center;
}
.input_form .input_bar {
width: 80%;
height: 50px;
font-size: 18px;
border: none;
}
.input_form button {
width: 10%;
height: 50px;
float: right;
margin-right: 30px;
}
</style>
<html>
<head>
</head>
<body>
<div class="container">
<div class="heading">
<h1>TO-DO LIST</h1>
</div>
<div class="item-list">
<div>
<p>TEEXT2</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
<div>
<p>TEEXT1</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
<div>
<p>TEEXT3</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
<div>
<p>TEEXT4</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
</div>
<div class="input_form">
<input type="text" class="input_bar" id="myText" placeholder="Add ITEM">
<button class="submit">+ADD ITEM</button>
</div>
</div>
</body>
</html>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
<div>
<p>TEEXT1</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
<div>
<p>TEEXT3</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
<div>
<p>TEEXT4</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
</div>
<div class="input_form">
<input type="text" class="input_bar" id="myText" placeholder="Add ITEM">
<button class="submit">+ADD ITEM</button>
</div>
<script src="script.js"></script>
</div>
</body>
</html>`
You actually only trigger DOM "original" delete button (button loaded with your HTML code) with the line :
let deleteText = document.querySelectorAll('.delete'); // delete button
Your others .delete are loaded after the first DOM loading and are not even listed in "deleteText" array !
You have to refresh deleteText every time you add a new item. Something like :
const itemsLIst = document.querySelector('.item-list'); // where we want to add our list
const addText = document.querySelector('.submit'); // add button
let deleteText = document.querySelectorAll('.delete'); // delete button
// const list = JSON.parse(localStorage.getItem('items')) || [];
let list = [];
function addItem(e) {
let text = document.querySelector('.input_bar').value; //text typed in input bar
if (text.length != 0) {
list.push(`<div>
<p>${text}</p>
<button class="delete" onclick='deleteItem'>🗴</button>
<button class="edit">Edit</button>
</div><hr>`);
itemsLIst.innerHTML = list.join('');
text = '0';
document.getElementById("myText").value = "";
} else {
return;
}
}
function deleteItem(e) {
this.parentElement.style.display = 'none';
}
function triggerDeleteButton(){
deleteText = document.querySelectorAll('.delete'); // delete button
for (var i = 0 ; i < deleteText.length; i++) {
deleteText[i].addEventListener('click', deleteItem);
}
}
addText.addEventListener('click', function(){
addItem() ;
triggerDeleteButton() ;
}
);
Without refreshing, you can add and edit data by using local storage
For example, like below, you can try once!
<script>
let customerData = [];
// Inserting new customer record into local storage
function insert() {
let company = document.getElementById("company").value;
let obj = {company};
customerData.push(obj);
synData(customerData);
let customerDetails = JSON.parse(localStorage.getItem("customerString"));
clearFileds();
displayelements(customerDetails);
}
function displayelements(customerDetails) {
let html = "<table id='customer_data' border='1'><tr><th>Sl No</th><th>Company</th><th>Delete</th></tr>";
if(customerDetails == '') {
html+="<tr>No record found!</tr>";
} else {
customerDetails.map((values, index) => {
html+="<tr id='row_data'>";
html+="<td>"+index+"</td>";
html+="<td>"+values.company+"</td>";
html+="<td onclick='deleteRow(" + index + ")'>Delete</td>";
html+="</tr>";
} )
}
html+="</table>";
document.getElementById("display").innerHTML = html;
clearFileds();
}
// Delete the specific customer record from local storage
function deleteRow(deleteKey) {
let customerDetails = JSON.parse(localStorage.getItem("customerString"));
customerDetails.map((values, index) => {
if (index == deleteKey) {
customerDetails.splice(index, 1);
}
})
customerData = customerDetails;
synData(customerDetails);
displayelements(customerDetails);
}
// Clearing the form input field data
function clearFileds() {
document.getElementById("company").value = '';
}
// Updating local storage data
function synData(customerDetails) {
localStorage.setItem('customerString', JSON.stringify(customerDetails));
}
</script>
<html>
<head>
<title>Save</title>
</head>
<script ></script>
<body id="format_background">
<div id="customerAction" >
<h1>Customer data</h1>
<label>Company Name </label>
<input id="company" type="text" />
<button type="button" value="Save&Show" onclick="insert()" id="insert">Save</button>
</div>
<div id="display"></div>
</body>
</html>
I'm new to CSS. I'm trying to create a nice grid that changes based on the user input. Here is my approach to this:
Create the "biggest" grid and set everything to be hidden.
When the user input changes, display the cells that required to be displayed. Also, change the margin accordingly.
I noticed that when I follow that logic, my cells somehow being push in a direction. It almost like the hidden cells still taking space somehow. Is there anyway to avoid this?
Here's my attempt:
'use strict'
let topBtn = document.querySelector("#top-btn");
let greyBar = document.querySelector("#grey-bar");
let topBtnClicked = false;
let gridSelectionBtns = document.querySelectorAll(".grid-selection-btn");
let mediaContainer = document.querySelector("#media-container");
let mediaCells = document.querySelectorAll(".media-cell");
function onTopBtnMouseEvent(ev) {
if (ev.type === "click") {
topBtn.style.opacity = "0.7";
greyBar.style.opacity = "0.7";
topBtnClicked = true;
} else if (ev.type === "mouseover") {
topBtn.style.opacity = "0.7";
} else if (ev.type === "mouseout") {
if (!topBtnClicked) {
topBtn.style.opacity = "0";
}
}
}
function onTopBarMouseEvent(ev) {
if (ev.type === "mouseover") {
} else if (ev.type === "mouseout") {
if (topBtnClicked && !(greyBar.contains(ev.relatedTarget) || (ev.relatedTarget === topBtn))) {
topBtnClicked = false;
topBtn.style.opacity = "0";
greyBar.style.opacity = "0";
}
}
}
function enableMediaCell(cellNumber, isEnable) {
let cell = mediaCells[cellNumber];
if (isEnable) {
cell.style.visibility = "visible";
cell.style.margin = "25px";
cell.style.gridGap = "10px";
} else {
cell.style.visibility = "hidden";
cell.style.margin = "0";
cell.style.gridGap = "0";
}
}
function gridSelectedHandler(type) {
if (!topBtnClicked) {
return;
}
switch (type) {
case 0:
mediaContainer.style.opacity = "1";
enableMediaCell(0, true);
for (let i = 1; i < mediaCells.length; ++i) {
enableMediaCell(i, false);
}
mediaContainer.style.gridTemplateColumns = "repeat(1, 1fr)";
mediaContainer.style.gridTemplateRows = "repeat(1, 1fr)";
break;
case 1:
mediaContainer.style.opacity = "1";
enableMediaCell(0, true);
enableMediaCell(1, true);
for (let i = 2; i < mediaCells.length; ++i) {
enableMediaCell(i, false);
}
mediaContainer.style.gridTemplateColumns = "repeat(2, 1fr)";
mediaContainer.style.gridTemplateRows = "repeat(1, 1fr)";
break;
case 2:
mediaContainer.style.opacity = "1";
for (let i = 0; i < 4; ++i) {
enableMediaCell(i, true);
}
for (let i = 4; i < mediaCells.length; ++i) {
enableMediaCell(i, false);
}
mediaContainer.style.gridTemplateColumns = "repeat(2, 1fr)";
mediaContainer.style.gridTemplateRows = "repeat(2, 1fr)";
break;
case 3:
mediaContainer.style.opacity = "1";
for (let i = 0; i < 6; ++i) {
enableMediaCell(i, true);
}
for (let i = 6; i < mediaCells.length; ++i) {
enableMediaCell(i, false);
}
mediaContainer.style.gridTemplateColumns = "repeat(3, 1fr)";
mediaContainer.style.gridTemplateRows = "repeat(2, 1fr)";
break;
case 4:
mediaContainer.style.opacity = "1";
for (let i = 0; i < mediaCells.length; ++i) {
enableMediaCell(i, true);
}
mediaContainer.style.gridTemplateColumns = "repeat(3, 1fr)";
mediaContainer.style.gridTemplateRows = "repeat(3, 1fr)";
break;
default:
break;
}
}
for (let i = 0; i < gridSelectionBtns.length; ++i) {
gridSelectionBtns[i].addEventListener("click", function() {
gridSelectedHandler(i)
})
}
document.addEventListener('keydown', function(e) {
if (e.key === 'Escape') {
mediaContainer.style.opacity = "0"
}
});
topBtn.onmouseover = topBtn.onmouseout = topBtn.onclick = onTopBtnMouseEvent;
greyBar.onmouseover = greyBar.onmouseout = greyBar.onclick = onTopBarMouseEvent;
body {
background-image: url("../media/gopher_background.jpg");
background-size: cover;
}
#top-btn {
width: 100%;
height: 25px;
opacity: 0;
background-image: url("../media/down-arrow.svg");
background-repeat: no-repeat;
background-position: center;
}
#grey-bar {
background-color: GhostWhite;
width: 100%;
height: 50px;
opacity: 0;
display: flex;
justify-content: center;
}
.grid-selection-btn {
width: 5%;
height: 100%;
margin: 0 1%;
}
#media-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(3, 1fr);
opacity: 0;
min-height: 85vh;
background-color: lightgray;
}
.media-cell {
background-color: lightgray;
visibility: hidden;
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-template-rows: repeat(2, 1fr);
grid-gap: 10px;
margin: 25px;
}
.youtube-btn {
/*background-image: url("../media/youtube-logo.png");*/
background-repeat: no-repeat;
background-position: center;
background-size: contain;
margin: 0 0 0 0;
padding: 0 0 0 0;
}
.reddit-btn {
/*background-image: url("../media/reddit-icon.png");*/
background-repeat: no-repeat;
background-position: center;
background-size: contain;
margin: 0 0 0 0;
padding: 0 0 0 0;
}
.twitter-btn {
/*background-image: url("../media/twitter.png");*/
background-repeat: no-repeat;
background-position: center;
background-size: contain;
margin: 0 0 0 0;
padding: 0 0 0 0;
}
.insta-btn {
/*background-image: url("../media/insta-logo.png");*/
background-repeat: no-repeat;
background-position: center;
background-size: contain;
margin: 0 0 0 0;
padding: 0 0 0 0;
}
<button id="top-btn"></button>
<div id="grey-bar">
<button class="grid-selection-btn">1</button>
<button class="grid-selection-btn">2</button>
<button class="grid-selection-btn">3</button>
<button class="grid-selection-btn">4</button>
<button class="grid-selection-btn">5</button>
</div>
<div id="media-container">
<div class="media-cell">
<button class="youtube-btn"></button>
<button class="reddit-btn"></button>
<button class="insta-btn"></button>
<button class="twitter-btn"></button>
</div>
<div class="media-cell">
<button class="youtube-btn"></button>
<button class="reddit-btn"></button>
<button class="insta-btn"></button>
<button class="twitter-btn"></button>
</div>
<div class="media-cell">
<button class="youtube-btn"></button>
<button class="reddit-btn"></button>
<button class="insta-btn"></button>
<button class="twitter-btn"></button>
</div>
<div class="media-cell">
<button class="youtube-btn"></button>
<button class="reddit-btn"></button>
<button class="insta-btn"></button>
<button class="twitter-btn"></button>
</div>
<div class="media-cell">
<button class="youtube-btn"></button>
<button class="reddit-btn"></button>
<button class="insta-btn"></button>
<button class="twitter-btn"></button>
</div>
<div class="media-cell">
<button class="youtube-btn"></button>
<button class="reddit-btn"></button>
<button class="insta-btn"></button>
<button class="twitter-btn"></button>
</div>
<div class="media-cell">
<button class="youtube-btn"></button>
<button class="reddit-btn"></button>
<button class="insta-btn"></button>
<button class="twitter-btn"></button>
</div>
<div class="media-cell">
<button class="youtube-btn"></button>
<button class="reddit-btn"></button>
<button class="insta-btn"></button>
<button class="twitter-btn"></button>
</div>
<div class="media-cell">
<button class="youtube-btn"></button>
<button class="reddit-btn"></button>
<button class="insta-btn"></button>
<button class="twitter-btn"></button>
</div>
</div>
I have been learning web dev for about 2 weeks now. I realize that my code might not be the best practice. I would love to receive some feedback on that too.
You observed correctly, the hidden elements are still taking space. That is the case with visibility: hidden ... to have an element not be visible or take space on the page at all, you want display: none. The default value for the display attribute of a div is block, so you could use that to make a cell visible in the script.
hi so this is my js and the problem i have is my js works fine with the first div but it has no effect on the other divs, and i cant seem to find whats the problem. i guess i know what the problem is the only issue i have is i dont know how to solve it, i would appreciate it if u could help me
this is my js:
var incrementerHandle = document.querySelector('.incrementer .value');
var incrementValue = document.querySelector('.incrementer .value span');
var downButton = document.querySelector('.incrementer .down');
var upButton = document.querySelector('.incrementer .up');
var peek = document.querySelector('.incrementer .peek'); //Handle Bounds
var neutral = '50%';
var upper = 50;
var lower = 10; //Count Bounds
var count = 0;
var minCount = 0;
var maxCount = 100; //Timer for holding
var timer;
downButton.addEventListener('click', incrementDown);
upButton.addEventListener('click', incrementUp);
function dragEndHandler() {
peek.classList.remove('active');
checkPosition();
clearInterval(timer); //Return to neutral
incrementerHandle.style.left = neutral;
}
function timerTick() {
peek.classList.add('active');
checkPosition();
}
function checkPosition() {
if (dragger.position.x >= upper) {
incrementUp();
} else if (dragger.position.x <= lower) {
incrementDown();
}
}
function incrementUp() {
count++;
if (count > maxCount) {
count = maxCount;
}
updateValue();
}
function incrementDown() {
count--;
if (count < minCount) {
count = minCount;
}
updateValue();
}
function updateValue() {
incrementValue.innerHTML = count;
checkDisplay();
}
function checkDisplay() {
if (count <= minCount) {
downButton.classList.add('disabled');
} else if (count >= maxCount) {
upButton.classList.add('disabled');
} else {
downButton.classList.remove('disabled');
upButton.classList.remove('disabled');
}
}
<div class="slider">
<div class="incrementer">
<button class="mdc-button mdc-button--raised up">
<span class="mdc-button__ripple">+</span>
</button>
<button class="value">
<span>0</span>
</button>
<button class="mdc-button mdc-button--raised down">
<span class="mdc-button__ripple">-</span>
</button>
</div>
</div>
Based on your explanation on the comment line, you have multiple divs with class slider with similar implementation as the one you posted. In this case you would have to use querySelectorAll() which returns a node list, rather than using querSelector() which returns a single element. I have made a few more adjustments accordingly.
var downButton = document.querySelectorAll('.incrementer .down');
var upButton = document.querySelectorAll('.incrementer .up');
var peek = document.querySelector('.incrementer .peek'); //Handle Bounds
var neutral = '50%';
var upper = 50;
var lower = 10; //Count Bounds
var minCount = 0;
var maxCount = 100; //Timer for holding
var timer;
downButton.forEach( down => down.addEventListener('click', incrementDown));
upButton.forEach( up => up.addEventListener('click', incrementUp));
function dragEndHandler() {
peek.classList.remove('active');
checkPosition();
clearInterval(timer); //Return to neutral
incrementerHandle.style.left = neutral;
}
function timerTick() {
peek.classList.add('active');
checkPosition();
}
function checkPosition() {
if (dragger.position.x >= upper) {
incrementUp();
} else if (dragger.position.x <= lower) {
incrementDown();
}
}
function incrementUp(e) {
let element = e.target;
let count = 0;
if( element.classList.contains('mdc-button') ){
count = Number( element.nextElementSibling.firstElementChild.innerHTML ) + 1;
if (count > maxCount) {
count = maxCount;
}
element.nextElementSibling.firstElementChild.innerHTML = count;
checkDisplay(count, element);
}
else {
count = Number( element.parentElement.nextElementSibling.firstElementChild.innerHTML ) + 1;
if (count > maxCount) {
count = maxCount;
}
element.parentElement.nextElementSibling.firstElementChild.innerHTML = count;
checkDisplay(count, element.parentElement);
}
}
function incrementDown(e) {
let element = e.target;
let count = 0;
if( element.classList.contains('mdc-button') ){
count = Number( element.previousElementSibling.firstElementChild.innerHTML ) - 1;
if (count < minCount) {
count = minCount;
}
element.previousElementSibling.firstElementChild.innerHTML = count;
checkDisplay(count, element);
}
else {
count = Number( element.parentElement.previousElementSibling.firstElementChild.innerHTML ) - 1;
if (count < minCount) {
count = minCount;
}
element.parentElement.previousElementSibling.firstElementChild.innerHTML = count;
checkDisplay(count, element.parentElement);
}
}
function checkDisplay(count, element) {
if (count <= minCount) {
element.classList.add('disabled');
} else if (count >= maxCount) {
element.classList.add('disabled');
} else {
element.classList.remove('disabled');
element.classList.remove('disabled');
}
}
#con{
border: 1px solid black;
padding: 10px;
width: 65%;
margin: 0 auto;
display: flex;
flex-direction: column;
justify-content: space-around;
text-align: center;
}
#con1{
border: 1px solid black;
flex-wrap: wrap;
display: flex;
flex-direction: row;
justify-content: space-around;
padding: 5px;
}
button{
background-color: #4CAF50; /* Green */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
select{
margin-top: 20px;
}
.redbu{
background-color: red;
}
.bluebu{
background-color: royalblue;
}
.greenbu{
background-color: #4CAF50;
}
.yellowbu{
background-color: yellow;
}
<div class="slider">
<div class="incrementer">
<button class="mdc-button mdc-button--raised up">
<span class="mdc-button__ripple">+</span>
</button>
<button class="value">
<span>0</span>
</button>
<button class="mdc-button mdc-button--raised down">
<span class="mdc-button__ripple">-</span>
</button>
</div>
</div>
<div class="slider">
<div class="incrementer">
<button class="mdc-button mdc-button--raised up">
<span class="mdc-button__ripple">+</span>
</button>
<button class="value">
<span>0</span>
</button>
<button class="mdc-button mdc-button--raised down">
<span class="mdc-button__ripple">-</span>
</button>
</div>
</div>
<div class="slider">
<div class="incrementer">
<button class="mdc-button mdc-button--raised up">
<span class="mdc-button__ripple">+</span>
</button>
<button class="value">
<span>0</span>
</button>
<button class="mdc-button mdc-button--raised down">
<span class="mdc-button__ripple">-</span>
</button>
</div>
</div>
I'm new to Javascript and I'm struggling to make something work.
I have a basic word game that is supposed to replace one character and the user has to guess that one. It works well (apart from obvious design errors, never mind these) if I specify ONE word only. However, I've spent all day to work through an array of words.
The user should see the (gapped) word, enter the missing character and should then be presented with the next gapped word until the array is finished.
This is the (fairly ok) code for the single word:
<html>
<body>
<h1> Guess the word! :) </h1>
<br><br>
<div id="paste_game" style="left: 30%; top: 25%; border: 3px solid #73AD21; font-size: 350%; font-weight: bold; display: flex; align-items: center; justify-content: center">
</div>
<br>
<br> feedback:
<div id="feedback" style="top: 35%; font-size: 150%; font-weight: bold; background-color:powderblue; display: flex; align-items: center; justify-content: center">
... feedback ...
</div>
<br> number of attempts:
<div id="attempts" style="top: 35%; font-size: 150%; font-weight: bold; background-color:powderblue; display: flex; align-items: center; justify-content: center">
... attempts ...
</div>
<div id="guess_area" style="height: 10em; display: flex; align-items: center; justify-content: center">
<h2>ENTER THE MISSING CHARACTER: </h2><br>
<input type="text" id="guess"><br>
<button onClick="guessChar()">GUESS!</button>
</div>
<script>
var testword = "straightforward";
var current_blank = getBlank(testword);
document.getElementById("paste_game").innerHTML = replaceChar(testword);
var count = 0;
function getBlank(word) {
var numchars = word.length;
var randomchar = Math.floor((Math.random() * numchars) + 1);
var chosenchar = word.charAt(randomchar);
return chosenchar;
}
function replaceChar(word) {
var newWord = word.replace(current_blank, "[ ]");
return newWord;
}
function guessChar() {
var char = document.getElementById("guess").value;
if (char == current_blank) {
document.getElementById("feedback").innerHTML = "Correct, the missing blank is >>" + char +"<<";
document.getElementById("paste_game").innerHTML = testword;
}
else if (char != current_blank) {
if (count < 2) {
document.getElementById("feedback").innerHTML = "Sorry, try again!";
// reset only works with forms, form breaks code
//document.getElementById("form").reset();
count++;
document.getElementById("attempts").innerHTML = count;
}
else {
document.getElementById("feedback").innerHTML = "Sorry, you've tried too often!";
count++;
document.getElementById("attempts").innerHTML = count;
}
}
else {
alert("ERROR");
}
}
</script>
</body>
</html>
This is the messed up code with an array (I stopped working on it in-between)
<html>
<body>
<h1> Guess the word! :) </h1>
<div id="start_div" style="height: 40px; display: flex; align-items: center; justify-content: center">
<button id="start_button" onClick="startGame()">START GAME!</button>
</div>
<div id="next_div" style="height: 60px; display: flex; align-items: center; justify-content: center">
<button id="start_button" onClick="nextWord()">NEXT WORD!</button>
</div>
<div id="paste_game" style="left: 30%; top: 25%; border: 3px solid #73AD21; font-size: 350%; font-weight: bold; display: flex; align-items: center; justify-content: center">
</div>
<br>
<br> feedback:
<div id="feedback" style="top: 35%; font-size: 150%; font-weight: bold; background-color:powderblue; display: flex; align-items: center; justify-content: center">
... feedback ...
</div>
<br> number of attempts:
<div id="attempts" style="top: 35%; font-size: 150%; font-weight: bold; background-color:powderblue; display: flex; align-items: center; justify-content: center">
... attempts ...
</div>
<div id="guess_area" style="height: 10em; display: flex; align-items: center; justify-content: center">
<h2>ENTER THE MISSING CHARACTER: </h2><br>
<input type="text" id="guess"><br>
<button onClick="guessChar()">GUESS!</button>
</div>
<script>
// define variables
//var guess_word = "straightforward";
var guessword_array = ['handy', 'lovely', 'annoying', 'superb'];
var global_chosen_char;
var count = 0;
var game_started = false;
var game_word;
var guessed_char;
var current_word;
var loopy;
/**
for (var i = 0; i < guessword_array.length; i++) {
array_current_position = guessword_array[i];
console.log("Array currently at "+guessword_array[i]+", position: "+i);
document.getElementById("paste_game").innerHTML = replaceChar(guessword_array[i]);
}
**/
/**
var tempword = replaceChar(guessword_array[i]);
document.getElementById("paste_game").innerHTML = tempword;
**/
// FUNCTION: get random character from word (=1) and replace by [] (=2)
function replaceChar(word) {
//1
var numchars = word.length;
var randompos = Math.floor((Math.random() * numchars) + 1);
if (randompos == numchars) {
randompos = 0;
}
//2
var chosenchar = word.charAt(randompos);
var newword = word.replace(chosenchar, "[]");
global_chosen_char = chosenchar;
global_newword = newword;
return newword;
}
// FUNCTION: first time the game is started
function startGame() {
if (guessed_char == undefined) {
alert("Thank you for playing!\nPlease start guessing and enter your guess below!");
current_word = guessword_array[0];
game_word = replaceChar(guessword_array[0]);
document.getElementById("paste_game").innerHTML = game_word;
console.log(game_word);
game_started = true;
return;
}
else {
alert("Sorry, an error has occurred!");
}
}
function nextWord() {
for (var i = 1; i < guessword_array.length; i++) {
game_word = replaceChar(guessword_array[i]);
console.log("nextword: "+game_word);
wait(100);
document.getElementById("paste_game").innerHTML = game_word;
guessChar();
}
}
function guessChar() {
if (game_started != true) {
startGame();
}
else if (game_started == true && guessed_char != "") {
guessed_char = document.getElementById("guess").value;
if (guessed_char == global_chosen_char) {
document.getElementById("feedback").innerHTML = "Correct! ".fontcolor("green")+"The word is: "+""+current_word.fontcolor("red").fontsize(20);
guessed_char = "";
console.log("Guessed char:" +guessed_char);
console.log("guessed righ");
}
else {
if (count < 2) {
document.getElementById("feedback").innerHTML = "Sorry, try again!".fontcolor("red");
count++;
document.getElementById("attempts").innerHTML = count;
}
else {
document.getElementById("feedback").innerHTML = "Sorry, you've tried too often!";
count++;
document.getElementById("attempts").innerHTML = count;
console.log("guessed wrong");
guessed_char = "";
}
}
}
else if (game_started == true && guessed_char == "") {
alert("Guess char is empty");
}
}
</script>
Please help me, I've already lost so much time on this - thank you so much!!!
P.S.: I know that there are some other issues with my code, but please focus on the array thing for now - thank you ever so much!
I modified it to use a list, also it uses an interval to switch to the next word.
The code could obviously use optimization, but I'm not going to go that far.
<html>
<body>
<h1> Guess the word! :) </h1>
<br><br>
<div id="paste_game" style="left: 30%; top: 25%; border: 3px solid #73AD21; font-size: 350%; font-weight: bold; display: flex; align-items: center; justify-content: center">
</div>
<br>
<br> feedback:
<div id="feedback" style="top: 35%; font-size: 150%; font-weight: bold; background-color:powderblue; display: flex; align-items: center; justify-content: center">
... feedback ...
</div>
<br> number of attempts:
<div id="attempts" style="top: 35%; font-size: 150%; font-weight: bold; background-color:powderblue; display: flex; align-items: center; justify-content: center">
... attempts ...
</div>
<div id="guess_area" style="height: 10em; display: flex; align-items: center; justify-content: center">
<h2>ENTER THE MISSING CHARACTER: </h2><br>
<input type="text" id="guess"><br>
<button onClick="guessChar()">GUESS!</button>
</div>
<script>
var words = ["straightforward", "testing"];
var currentWord = 0;
var current_blank = getBlank(words[currentWord]);
document.getElementById("paste_game").innerHTML = replaceChar(words[currentWord]);
var count = 0;
function getBlank(word) {
var numchars = word.length;
var randomchar = Math.floor((Math.random() * numchars) + 1);
var chosenchar = word.charAt(randomchar);
return chosenchar;
}
function replaceChar(word) {
var newWord = word.replace(current_blank, "[ ]");
return newWord;
}
function guessChar() {
var char = document.getElementById("guess").value;
if (char == current_blank) {
document.getElementById("feedback").innerHTML = "Correct, the missing blank is >>" + char +"<<";
document.getElementById("paste_game").innerHTML = words[currentWord];
setTimeout(function(){
currentWord++;
current_blank = getBlank(words[currentWord]);
document.getElementById("paste_game").innerHTML = replaceChar(words[currentWord]);
}, 2000);
}
else if (char != current_blank) {
if (count < 2) {
document.getElementById("feedback").innerHTML = "Sorry, try again!";
// reset only works with forms, form breaks code
//document.getElementById("form").reset();
count++;
document.getElementById("attempts").innerHTML = count;
}
else {
document.getElementById("feedback").innerHTML = "Sorry, you've tried too often!";
count++;
document.getElementById("attempts").innerHTML = count;
}
}
else {
alert("ERROR");
}
}
</script>
</body>
</html>
You iterate over your array once and start all games at the same time. You may wait for the user to finish:
var words=["hi","test","abc"];
var current=0;
function next_word(){
current++;
var word=words[current];
....
}