Javascript misses some clicks - javascript

Hi I'm new to javascript, and trying to make a basic calculator
I started with the add button
When I run the code sometimes I have to click on the btn-add button twice or 3 times to display the result and the calculations when the number of digits of the input is greater than the previous result
Any ideas?
const addBtn = document.querySelector('#btn-add')
const userInput = document.querySelector('#input-number')
const currentResultOutput = document.querySelector('#current-result')
const currentCalculationOutput = document.querySelector('#current-calculation')
let currentResult = 0
let currentDescription
addBtn.addEventListener('click', addFn)
function addFn() {
currentDescription = ` ${currentResult} + ${userInput.value} `
currentResult += Number(userInput.value)
outputResult(currentResult, currentDescription)
}
function outputResult(result, text) {
currentResultOutput.innerHTML = result
currentCalculationOutput.innerHTML = text
}
<section id="calculator">
<input type="number" id="input-number" st />
<div id="calc-actions">
<button type="button" id="btn-add">+</button>
<button type="button" id="btn-subtract">-</button>
<button type="button" id="btn-multiply">*</button>
<button type="button" id="btn-divide">/</button>
</div>
</section>
<section id="results">
<h2 id="current-calculation">0</h2>
<h2>Result: <span id="current-result">0</span></h2>
</section>

it's an issue with the laptop mouse lmaoo, sorry guys

please replace this one
function addFn() {
currentDescription = ` ${currentResult} + ${userInput.value} `
currentResult += ParseInt(userInput.value)
outputResult(currentResult, currentDescription)
}
with this code
function addFn() {
currentDescription = ` ${currentResult} + ${userInput.value} `
currentResult += parseInt(userInput.value)
outputResult(currentResult, currentDescription)
}

Related

Current number of count in own div with Javascript

I am trying to add an increasing count number when a button is clicked, within the container <div>.
My code is not working, what am I missing?
let taskCounter = 0;
let addTaskFunction = () => {
const container = document.querySelector(".container");
taskCounter++;
let counterInDiv = document.createElement(`<div> ${taskCounter} </div>`);
container.appendChild(counterInDiv);
};
document.getElementById('addTask').addEventListener("click", () => {
addTaskFunction();
});
<h1>Your tasklist for today</h1>
<div class="container">
<div class="inputPart">
<input id="taskInput" value="" placeholder="Fill in the following task here" />
<button id="addTask">Add task</button>
<button id="removeAllTasks">Delete tasks</button>
</div>
</div>
You need to use the tag name (div) for document.createElement then set the innerHTML instead of using the actual HTML code.
let taskCounter = 0;
let addTaskFunction = () => {
const container = document.querySelector(".container");
taskCounter++;
let counterInDiv = document.createElement("div"); // <--HERE
counterInDiv.innerHTML = taskCounter;
container.appendChild(counterInDiv);
};
document.getElementById('addTask').addEventListener("click", () => {
addTaskFunction();
});
<body>
<h1>Your tasklist for today</h1>
<div class="container">
<div class="inputPart">
<input id="taskInput" value="" placeholder="Fill in the following task here" />
<button id="addTask">Add task</button>
<button id="removeAllTasks">Delete tasks</button>
</div>
</div>
<script src="app.js"></script>
</body>
I believe that this is the code you want:
let taskCounter = 1;
const taskList = document.getElementById("taskList");
const addTaskBtn = document.getElementById("addTask");
addTaskBtn.addEventListener("click", () => {
let task = document.getElementById("taskInput").value;
let counterInDiv = document.createElement("div");
counterInDiv.textContent = `${taskCounter++}: ${task}`;
taskList.appendChild(counterInDiv);
});
const deleteTasksBtn = document.getElementById("removeAllTasks");
deleteTasksBtn.addEventListener("click", () => {
taskList.innerHTML = "";
taskCounter = 1;
});
<h1>Your tasklist for today</h1>
<div class="container">
<div class="inputPart">
<input id="taskInput" placeholder="Fill in the following task here" />
<button id="addTask">Add task</button>
<button id="removeAllTasks">Delete tasks</button>
</div>
<div id="taskList"></div>
</div>
I made a few changes:
You do not need a function for the event listener, you can put the code inside an anonymous function that is passed to the event listener
taskCounter should start at 1, not 0
If you want the delete tasks button to work, then you should put the tasks inside a different container that can be easily cleared. I used one with the ID of "taskList"
document.querySelector() only selects a single element, but you gave it a class of "container". If multiple <div>s have the class "container", then you will run into problems.
document.createElement takes a tag name as the parameter, not HTML code. You should use document.createElement("div") then set the .textContent to whatever you want.

Multiply a variable and store that value/output to screen

I have tried a bunch of ways to get this to work. I'm not a coder, and I have a frankensteined abomination of a counter program I put together as a replacement for our expensive counters that kept breaking on us (basically you input a value at the start of the day, and based on that value a calculation is done for the GOAL for the day).
I now want to add a GOAL BY LUNCH field/display that - however simply doing something like
var lunchgoal = goal * 0.69;
And then putting it on the page like I have with the goal field, does not seem to work.
I can either get it to display 0 - which seems like its displaying just the basic 0 value of goal before it is being incremented, or NaN - not a number.
So I thought I need to convert it to a number before multiplying it, but I nothing has worked for me for that. Right now I'm guessing it may be a matter of where they are contained on the page? I find that part of this confusing honestly. Any help is much appreciated, I would have thought this would be fairly simple!
Thank you!
HTML
<html>
<style>
body {background-color: Black;}
p {color: white;}
</style>
<div class="container">
<p> SAMS VALUE: <span id="output"> </span>
</p>
<p style="font-size:110px"> GOAL: <span id="output2"> </span>
</p>
<button style="background-color:white;width:20%;height:15%;font-size: 60px" type="button" onClick="onClick()">ACTUAL</button>
<p style="font-size:110px">Actual Count: <span id="clicks">0</span>
</p>
<div class="row">
<div class="col-sm-4"/>
<div class="col-sm-4">
<div id="timeContainer" class="well well-sm">
<time id="timerValue"/>
</div>
<div id="timerButtons">
<button id="start" class="btn btn-success" disabled="disabled">START</button>
<button id="stop" class="btn btn-danger">STOP</button>
<button id="reset" class="btn btn-default">RESET</button>
</div>
<div class="col-sm-4 col-sm-4 col-md-4"/>
</div>
</div>
</div>
</html>
Script
<script type="text/javascript">
document.addEventListener("keyup", function(event) {
if (event.keyCode === 109) {
event.preventDefault();
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
}
});
document.addEventListener("keyup", function(event) {
if (event.keyCode === 107) {
event.preventDefault();
document.getElementById("stop").click();
}
});
var clicks = 0;
function onClick() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
const input = parseInt(prompt("Enter a SAMS number: "));
var SAMSINPUT = input;
console.log(SAMSINPUT);
document.getElementById('output').innerHTML = SAMSINPUT;
var goal = 0;
var output2 = document.getElementById('output2');
//set interval for GOAL calculation
var samsInterval = setInterval(function doIncrement() {
if (clear == false) {
goal += 1;
output2.innerHTML = goal.toString();
}
}, SAMSINPUT * 1000);
var timerDiv = document.getElementById('timerValue'),
start = document.getElementById('start'),
stop = document.getElementById('stop'),
reset = document.getElementById('reset'),
clear = false,
t;
</script>
You have to do it in loop where goal is changing & you want this to change as well.otherwise it just stays on 0. i shortened the timer for demo purpose
document.addEventListener("keyup", function(event) {
if (event.keyCode === 109) {
event.preventDefault();
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
}
});
document.addEventListener("keyup", function(event) {
if (event.keyCode === 107) {
event.preventDefault();
document.getElementById("stop").click();
}
});
var clicks = 0;
function onClick() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
const input = parseInt(prompt("Enter a SAMS number: "));
var SAMSINPUT = input;
// console.log(SAMSINPUT);
document.getElementById('output').innerHTML = SAMSINPUT;
var goal = 0;
var output2 = document.getElementById('output2');
//set interval for GOAL calculation
var samsInterval = setInterval(function doIncrement() {
if (clear == false) {
goal += 1;
output2.innerHTML = goal.toString();
var lunchGoalNumber = goal * 0.69;
var output3 = document.getElementById("output3")
output3.innerHTML = lunchGoalNumber;
}
}, SAMSINPUT * 25);
var timerDiv = document.getElementById('timerValue'),
start = document.getElementById('start'),
stop = document.getElementById('stop'),
reset = document.getElementById('reset'),
clear = false;
<div class="container">
<p> SAMS VALUE: <span id="output"> </span></p>
<p style="font-size:50px"> GOAL: <span id="output2"> </span></p>
<p style="font-size:50px"> Lunch/GOAL: <span id="output3"> </span></p>
<button style="background-color:white;width:35%;height:15%;font-size: 60px" type="button" onClick="onClick()">ACTUAL</button>
<p style="font-size:50px">Actual Count: <span id="clicks">0</span></p>
<div class="row">
<div class="col-sm-4"></div>
<div class="col-sm-4">
<div id="timeContainer" class="well well-sm">
<time id="timerValue"></time>
</div>
<div id="timerButtons">
<button id="start" class="btn btn-success" disabled="disabled">START</button>
<button id="stop" class="btn btn-danger">STOP</button>
<button id="reset" class="btn btn-default">RESET</button>
</div>
<div class="col-sm-4 col-sm-4 col-md-4"></div>
</div>
</div>
</div>
</body>

How to update variable number inside of eventlistner with condinitional statement

Please excuse me as if this seems like a simple question. I want to update the sum every time the space bar key is pressed down along with updating the innerHTML. Whenever I press the spacebar it just concatenates my sum variable instead of simply adding it.
HTML
<div class="sec1 sec">
<h1>Spacebar Challenge</h1>
</div>
<div class="sec2 sec">
<p>
You have hit the spacebar <span>0</span> times.
</p>
<div class='button'><button>Restart</button> </div>
</div>
<div class="sec3 sec"></div>
<script src="app.js"></script>
JS
let span = document.querySelector("span")
document.body.addEventListener("keyup", function (e) {
let sum = 0
if (e.code === "Space") {
sum += 1
}
span.innerHTML += sum
})
Try:
let span = document.querySelector("span")
let sum = 0
document.body.addEventListener("keyup", function(e) {
if (e.code === "Space") {
sum += 1
}
span.innerHTML = sum
})
<div class="sec1 sec">
<h1>Spacebar Challenge</h1>
</div>
<div class="sec2 sec">
<p>
You have hit the spacebar <span>0</span> times.
</p>
<div class='button'><button>Restart</button> </div>
</div>
<div class="sec3 sec"></div>
<script src="app.js"></script>

Adding together any number of items in an array with Javascript

I am learning Javascript and currently having an issue creating an application. I want to create a webpage that will take the values entered in a textbox, and place them inside an array. Then, I want to create a function that will add the values together. I am nearly complete, but I am having a tough time figuring out how to create a function that will add together the array items. My biggest issue is that any number of values can be entered into the page, and all the documentation I can find is based on having a pre-set array. Here is my code:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Numbers</title>
</head>
<body>
<section>
<header class="header m-2" id="myForm">Numbers App</header>
<section class="row m-2">
<label class="inputLabel">Number: <input type="number" id="numInput"></label>
</section>
<button class="button m-1" onclick="displayText(); addNum(); testCount();" id="addButton">Add Number</button>
<button class="button m-1" disabled>Calculate</button>
<button class="button m-1" onclick="resetPage();">Reset</button>
</section>
<section id="numForm">
<div class="numLabel m-2" id="numLabel">Numbers Added: </div>
<p class="m-2 mt-3" id="numValue"></p>
</section>
<script src="script.js"></script>
</body>
</html>
JS:
//Display "Numbers Added: "
function displayText() {
document.getElementById("numLabel").style.display = "block";
}
//Add the entered values into the array
let numArray = [];
function addNum() {
let num = document.getElementById("numInput").value;
numArray.push(num);
document.getElementById("numValue").innerHTML = numArray.join(" ");
}
//Testing count function
function testCount() {
for(count = 0; count > 2; count++) {
console.log("this works");
}
}
//Reset the page
function resetPage() {
//Clear input field
document.getElementById("numInput").value = "";
//Hide "Numbers Added: "
document.getElementById("numLabel").style.display = "none";
//Clear array items
numArray = [];
document.getElementById("numValue").innerHTML = "";
}
Edit:
To display the addition can just use something like:
const array1 = [1, 2, 3, 4];
const result = array1.reduce((acc, curr) => parseInt(curr) + parseInt(acc));
let additionDisp = array1.join(" + ") + " = " + result;
console.log(additionDisp);
You need to declare your add function first, parse your string input to integer value and perform a reduction to get the sum
//Add the entered values into the array
let numArray = [];
//Display "Numbers Added: "
function displayText() {
var result = numArray.reduce((acc, curr) => parseInt(curr) + parseInt(acc), 0);
var numSumString = "";
for (data of numArray) {
numSumString = data + " + " + numSumString;
}
document.getElementById("numLabel").innerHTML = "Numbers Added:" + numSumString.substring(0, numSumString.length - 2) + "=" + result;
}
function addNum() {
let num = document.getElementById("numInput").value;
numArray.push(num);
document.getElementById("numValue").innerHTML = numArray.join(" ");
}
//Reset the page
function resetPage() {
//Clear input field
document.getElementById("numInput").value = "";
//Hide "Numbers Added: "
document.getElementById("numLabel").style.display = "none";
//Clear array items
numArray = [];
document.getElementById("numValue").innerHTML = "";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Numbers</title>
</head>
<body>
<section>
<header class="header m-2" id="myForm">Numbers App</header>
<section class="row m-2">
<label class="inputLabel">Number: <input type="number" id="numInput"></label>
</section>
<button class="button m-1" onclick="addNum();" id="addButton">Add Number</button>
<button class="button m-1" onclick="displayText();">Calculate</button>
<button class="button m-1" onclick="resetPage();">Reset</button>
</section>
<section id="numForm">
<div class="numLabel m-2" id="numLabel">Numbers Added: </div>
<p class="m-2 mt-3" id="numValue"></p>
</section>
<script src="script.js"></script>
</body>
</html>
Use Array.prototype.reduce.
const array = [0, 42, 101, 5, 2];
const total = array.reduce((sum, x) => sum + x);
console.log(total);

How to change multiple images by clicking button to change src in Javascript

I'm totally new to web dev and trying to learn and practice Javascript.
I've learned a trick to change displayed image by changing the src of the image (they are named: pic-0.jpg, pic-1.jpg, pic-2.jpg... so on) but somehow my code won't work.
Anyone can have a look at my codes, help me out and give me some advice. I'd appreciate it!
Here are the codes:
var counter = 0;
document.getElementById('btn-next').addEventListener('click', changeImg);
function changeImg() {
counter++;
document.getElementById('picture').src = 'pic-' + counter + '.jpg';
}
<body>
<section class="container">
<div class="picture-container">
<img src="pic-0.jpg" id="picture" alt="">
</div>
<button id="btn-previous">Previous</button>
<button id="btn-next">Next</button>
</section>
<script src="r.js"></script>
</body>
cheers and many thanks!
you are using getElementsById , you should use getElementById because id is always unique and one page can have only one id , you can use getElementsByClassName because class can be attached more than one tag
var counter = 0;
document.getElementById('btn-next').addEventListener('click', changeImg);
function changeImg() {
counter++;
document.getElementById('picture').src = 'pic-' + counter + '.jpg';
document.getElementById('picture').alt = 'pic-' + counter + '.jpg';
}
<body>
<section class="container">
<div class="picture-container">
<img src="pic-0.jpg" id="picture" alt="df">
</div>
<button id="btn-previous">Previous</button>
<button id="btn-next">Next</button>
</section>
<script src="r.js"></script>
</body>
//---------------------JavaScript---------------
<body>
<section class="container">
<div class="picture-container">
<img src="https://i.picsum.photos/id/1/5616/3744.jpg" id="picture" height=50 width=50 alt="df">
</div>
<button id="btn-previous">Previous</button>
<button id="btn-next">Next</button>
</section>
<script>
var counter = 1;
document.getElementById('btn-next').addEventListener('click', nextImg);
document.getElementById('btn-previous').addEventListener('click',preImg);
function nextImg() {
counter++;
document.getElementById('picture').src = 'https://i.picsum.photos/id/' + counter + '/5616/3744.jpg';
}
function preImg() {
counter--;
document.getElementById('picture').src = 'https://i.picsum.photos/id/' + counter + '/5616/3744.jpg';
}
</script>
</body>
I think the best thing is store all of your images path into an array. Then
var imgArr = ["1.jpg", "2.jpg"]
var counter = 0;
function changeImg(evt) {
if(evt === 'prv'){
if(counter === 1)
counter++;
else
counter--;
}
else{
if(counter === (imgArr.length))
counter = 1;
else
counter++;
}
document.getElementById('picture').src = imgArr[counter];
}
<section class="container">
<div class="picture-container">
<img src="" id="picture" alt="">
</div>
<button id="btn-previous" onClick="changeImg('prv')">Previous</button>
<button id="btn-next" onClick="changeImg('nxt')">Next</button>
</section>

Categories

Resources