How to show the total increment of an app counter - javascript

Guys I wanna make an app which can count people, I have it according to the course but I'd like to add the total at the end not the previous entries.
enter image description here
let saveEl = document.getElementById("save-el")
let countEl = document.getElementById("count-el")
let count = 0
function counter() {
count += 1
countEl.textContent = count
}
function save() {
//let countStr = count + "-" caso eu não queira que volte do zero
let countStr = count + " - "
saveEl.textContent += countStr
countEl.textContent = 0
count = 0
}
console.log(count)

Instructions were not clear but I guess you want to "sum up the counts" instead of displaying them separately.
Here's a codepen achieving that, hopefully that works for you ;)
let saveEl = document.getElementById("save-el")
let countEl = document.getElementById("count-el")
let count = 0
function counter() {
count += 1
countEl.textContent = count
}
function save() {
let prevCount = saveEl.textContent ? parseInt(saveEl.textContent) : 0
saveEl.textContent = count + prevCount
countEl.textContent = 0
count = 0
}
<!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>Counter</title>
</head>
<body>
<h1>Members :</h1>
<button onClick=counter()>counter</button>
<button onClick=save()>save</button>
<p id="count-el"></p>
<hr/>
<p id="save-el"></p>
</body>
</html>

Related

How to detect "+" in JavaScript and convert it to a number?

I have a script like this
let x;
let y;
let z;
let obliczone;
document.getElementById("srednia").onclick = function() {
x = document.getElementById("grade1").value;
y = document.getElementById("grade2").value;
z = document.getElementById("grade3").value;
x = Number(x);
y = Number(y);
z = Number(z);
obliczone = Number(obliczone);
obliczone = (x + y + z) / 3;
console.log(obliczone);
document.getElementById("wynik").innerHTML = "Twoja średnia to " + obliczone;
}
<!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="main.css">
<title>Document</title>
</head>
<body>
<label>Ocena 1</label> <input type="text" id="grade1"><br>
<label>Ocena 2</label> <input type="text" id="grade2"><br>
<label>Ocena 3</label> <input type="text" id="grade3"><br>
<label>Oblicz: </label> <button id="srednia">Średnia</button>
<p id="wynik"></p>
<script src="index.js"></script>
</body>
</html>
and if user type in a number with "+" like 2+ I want i to give me 2.5 value and if the input is higher than 6 to break the function. It meant to calculate arithmetic mean of 3 digits and as I wrote earlier it should change ex. 1+ to 1.5
By default when the JavaScript interpreter tries to cast the string to a number and this string contains a symbol it results in a NaN (Not a Number). You can do what you want by replacing the '+' symbol with '.5'.
The new code:
let x;
let y;
let z;
let obliczone;
document.getElementById("srednia").onclick = function () {
x = document.getElementById("grade1").value;
y = document.getElementById("grade2").value;
z = document.getElementById("grade3").value;
const doesXEndsWithPlus = x.endsWith('+')
const doesYEndsWithPlus = y.endsWith('+')
const doesZEndsWithPlus = z.endsWith('+')
if (doesXEndsWithPlus) x = x.replace('+', '.5')
if (doesYEndsWithPlus) y = y.replace('+', '.5')
if (doesZEndsWithPlus) z = z.replace('+', '.5')
x = Number(x);
y = Number(y);
z = Number(z);
obliczone = Number(obliczone);
obliczone = (x + y + z) / 3;
console.log(obliczone);
document.getElementById("wynik").innerHTML = "Twoja średnia to " + obliczone;
}
This is one way you can do it however if you end up putting more than 3 inputs it can start getting repetitive.
document.getElementById("srednia").onclick = function(){
let obliczone;
let x = document.getElementById("grade1").value;
let y = document.getElementById("grade2").value;
let z = document.getElementById("grade3").value;
if (x.includes('+')) {
x = parseFloat(x.split("+")[0] + ".5")
}
if (y.includes('+')) {
y = parseFloat(y.split("+")[0] + ".5")
}
if (z.includes('+')) {
z = parseFloat(z.split("+")[0] + ".5")
}
obliczone = (x+y+z) / 3;
console.log(obliczone);
document.getElementById("wynik").innerHTML = "Twoja średnia to " + obliczone;
}
One solution to make it cleaner and more dynamic is to create a helper function formatNumInput(input):
function formatNumInput(input) {
let newNum;
if (input.includes('+')) {
newNum = parseFloat(input.split("+")[0] + ".5")
} else {
newNum = parseFloat(input)
}
return newNum
}
document.getElementById("srednia").onclick = function(){
let obliczone;
let x = document.getElementById("grade1").value;
let y = document.getElementById("grade2").value;
let z = document.getElementById("grade3").value;
x = formatNumInput(x)
y = formatNumInput(y)
z = formatNumInput(z)
obliczone = (x+y+z) / 3;
console.log(obliczone);
document.getElementById("wynik").innerHTML = "Twoja średnia to " + obliczone;
}
I would like to propose you something a little bit different that could to inspired you and where are not you are not limited only to 3 values of ratings:
//here I define some globals variables
let evaluation = document.getElementById('eval');
let evaluations = [];
let showEval = document.getElementById("evaluation");
let addEval = document.getElementById("addEval");
let average = 0
function showEvals (){
for (let i = 0; i < evaluations.length; i++) {
showEval.innerHTML += `<span>${evaluations[i]}</span>, `
};
};// this is a function to show ratings
function countAverage () {
let sum = 0
for (let i = 0; i < evaluations.length; i++) {
const rating = parseFloat(evaluations[i],10)//here I convert a string go float (Numners() create variable type object not type number
sum += rating
average = (sum/evaluations.length).toFixed(2)// I limited my float to 2 digits
};
document.getElementById("result").innerHTML = "Twoja średnia to " + average
} // this function counts and shows average
addEval.onclick = function(){
evaluations.push(evaluation.value)
showEval.innerHTML = [];
showEvals();
countAverage();
};// here new rangs is pushed to the array of evaluations and it calls ather functions
<!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>
<script src="script.js" defer></script>
</head>
<!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>
<script src="script.js" defer></script>
</head>
<body>
<label for="eval">Dodaj ocene:</label>
<select name="evals" id="eval">
<option value="1">1</option>
<option value="1.5">1+</option>
<option value="2">2</option>
<option value="2.5">2+</option>
<option value="3">3</option>
<option value="3.5">3+</option>
<option value="4">4</option>
<option value="4.5">4+</option>
<option value="5">5</option>
<option value="5.5">5+</option>
<option value="6">6</option>
</select>
</select>
<button id="addEval">Dodaj ocene</button>
<h2>Twoje oceny to:</h2>
<div id="evaluation"></div>
<p id="result"></p>
</body>
</html>

running a setInterval function before previous instance is done on diffrent event.target

Im trying shuffle the words on mouseover, but to shuffle a new word the previous word have be finished shuffling. This is because otherwise i will get an event.target.innerHTML of a word made up of random letters, if i mouseover the word while the alogorithm is shuffling.
How can i get over this problem, and shuffle any word on mouseover unless that specific word is allready shuffling?
var interv = 'undefined'
var canChange = false
var globalCount = 0
var count = 0
var isGoing = false
document.querySelectorAll("span").forEach((button) => button.addEventListener("mouseover", shuffleWord));
let texxt = document.querySelector('p');
console.log(texxt);
function shuffleWord(event){
let INITIAL_WORD = event.target.innerHTML;
if(isGoing) return;
var randomWord = getRandomWord(INITIAL_WORD);
event.target.innerHTML = randomWord;
isGoing = true;
interv = setInterval(function() {
var finalWord = ''
for(var x=0;x<INITIAL_WORD.length;x++) {
if(x <= count && canChange) {
finalWord += INITIAL_WORD[x]
} else {
finalWord += getRandomLetter()
}
}
event.target.innerHTML = finalWord
if(canChange) {
count++
}
if(globalCount >= 20) {
canChange = true
}
if(count>=INITIAL_WORD.length) {
clearInterval(interv)
count = 0
canChange = false
globalCount = 0
isGoing = false
}
globalCount++
},40)
function getRandomLetter() {
var alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
return alphabet[rand(0,alphabet.length - 1)]
}
function getRandomWord(word) {
var text = word;
console.log(text);
INITIAL_WORD = event.target.innerText;
var finalWord = ''
for(var i=0;i<text.length;i++) {
finalWord += text[i] == ' ' ? ' ' : getRandomLetter()
}
return finalWord
}
function rand(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
}
<!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>
</head>
<body>
<span>SOME RANDOM TEXT</span>
<br>
<br>
<span>MORE TEXT</span>
<br>
<br>
<span>EVEN MORE TEXT</span>
<script src="script.js"></script>
</body>
</html>

how i am going to clearInterval when i press stop btn?

i am truly new with programing with javaScript so i just start to learn it, it will be good you are going to reply using a simple js code
my code does'nt stop when i press stop i want to clear the interval that i named with myTimer if i didn't put setInterval inside the function it just work directly and if there is any way to make my code more short please mentiot it.
const // my variable
myHour = document.getElementById("hours"),
myMin = document.getElementById("min"),
mySecond = document.getElementById("second"),
myMiliSecond = document.getElementById("dsecond"),
startchrono = document.getElementById("start"),
getLap = document.getElementById("lap"),
stopchrono = document.getElementById("stop"),
resetchrono = document.getElementById("reset"),
result = document.getElementById("result");
let // variable
milisecond = 0,
second = 0,
minute = 0,
hour = 0,
chronoRun = false,
round = 0;
function decoration(item) // this function is for add 0 if second or minute less than 10
{
if (String(item).length < 2) {
item = "0" + item;
}
return item;
}
function lapset() // function that create a new row in the table to save rounds
{
round++;
let // decoration add 0 if number under 10
ds = decoration(milisecond),
s = decoration(second),
m = decoration(minute),
h = decoration(hour);
if (round <= 10) {
const // insert the row in table
tr = result.insertRow(-1);
tr.insertCell(0).innerHTML = round;
tr.insertCell(-1).innerHTML = h + ":" + m + ":" + s + ":" + ds;
} else if (round <= 11) {
tr = result.insertRow(-1);
tr.insertCell(-0).innerHTML = "-";
tr.insertCell(-1).innerHTML = "you can't add any more laps";
getLap.setAttribute("disabled", "true");
}
}
function chrono() //chrono start
{
// chrono
milisecond++;
// make sure that minute, second have to be less than 60
if (milisecond > 10) {
milisecond = 0;
second++;
}
if (second > 59) {
second = 0;
minute++;
}
if (minute > 59) {
minute = 0;
hour++;
}
let // decoration add 0 if number under 10
ds = decoration(milisecond),
s = decoration(second),
m = decoration(minute),
h = decoration(hour);
myMiliSecond.innerHTML = ds;
mySecond.innerHTML = s;
myMin.innerHTML = m;
myHour.innerHTML = h;
startchrono.setAttribute("disabled", "true");
}
// function chronoStarts() {}
const myTimer = () => {
setInterval(chrono, 100);
};
const test = () => {
return clearInterval(myTimer);
};
startchrono.addEventListener("click", myTimer);
getLap.addEventListener("click", lapset);
stopchrono.addEventListener("click", test);
<!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>
</head>
<body>
<div id="chrono">
<div id="timer">
<span id="hours" class="time">00</span>
<span class="sep">:</span>
<span id="min" class="time">00</span>
<span class="sep">:</span>
<span id="second" class="time">00</span>
<span class="sep">:</span>
<span id="dsecond" class="time">00</span>
</div>
<div id="btnarea">
<button id="start" class="btnevent">start</button>
<button id="lap" class="btnevent">lap</button>
<button id="stop" class="btnevent">stop</button>
<button id="reset" class="btnevent">reset</button>
</div>
<table id="result">
<caption>saved lap</caption>
<tbody>
<tr>
<th class="round">round</th>
<th class="laptime">time</th>
</tr>
</tbody>
</table>
</div>
<script src="newpagescript.js"></script>
</body>
</html>
and that is my html code i think every is ok with my code but if there any issue i am looking for adives
You need to get the return value of the setInterval function and then pass that value as a parameter in the clearInterval function. For example, see below:
`// function chronoStarts() {}
let intervalId = 0;
const myTimer = () => {intervalId = setInterval(chrono, 100);};
const test = () => {
clearInterval(intervalId);
};
startchrono.addEventListener("click", myTimer);
getLap.addEventListener("click", lapset);
stopchrono.addEventListener("click", test);`

How to take user input as argument of function in JavaScript in order to implement Insertion Sort Algorithm?

Below is the function for insertion sort. I want that user should give the input from html form as an array elements instead of hard coding the elements of array. I have tried several techniques but in vain.
function insertionSort (inputArr) {
let length = inputArr.length;
for (let i = 1; i < length; i++) {
let key = inputArr[i];
let j = i - 1;
while (j >= 0 && inputArr[j] > key) {
inputArr[j + 1] = inputArr[j];
j = j - 1;
}
inputArr[j + 1] = key;
}
return inputArr;
};
let inputArr = [2,4,5,36,2,6,26,8,3,7]; // I want here user input which comes from html form instead of hard-coding elements of array like this
insertionSort(inputArr);
console.log(inputArr);
// Event listner
function getData() {
let userData = document.getElementById('data').value;
return userData;
}
<!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>Insertion Sort In JavaScript</title>
</head>
<body>
<h1>Insertion Sort in JavaScript</h1>
<form action="#">
<label for="data">Write Random Numbers</label>
<input type="text" name="data" id="data">
<button onclick="getData()">Submit</button>
</form>
<div id="printData"></div>
<script src="insertionsort.js"></script>

stop setTime from another function with local variable

thanks for helping!
The main goal of this is Stop the timer. But It does not work.
I know that this does not work because I am calling a local variable from another function but If I declare the variable as global the setTime starts automatically and It is not what I want.
How could a solve it, or another alternative? thanks!!
This is my code:
var interval2;
function startTimef(){
var startTime = Date.now();
interval2 = setInterval(function() {
var elapsedTime = Date.now() - startTime - 5000;
document.getElementById("timer").innerHTML = (elapsedTime / 1000).toFixed(3);
}, 75);
}
function myStopFunction(interval2) {
clearInterval(interval2); // does not work because interval2 is a local variable in StartTime.
var result = document.getElementById("result");
var score = document.getElementById("timer").textContent;
if (score < -0.200) { result.innerHTML = score+" Almost there ";}
if (score < -500 && score < -0.200) { result.innerHTML = "Almost there";}
if (score > -0.200 && score < 0 ) { result.innerHTML = "No too bad mate";}
if (score > -0.100 && score < 0.200 ) { result.innerHTML = "Perfect !!!";}
if (score > 0.200 ) { result.innerHTML = "You need some work!";}
};
// Press Enter Keyboard
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>TimeOver</title>
</head>
<body>
<div class="main-box">
<h2>Try to Stop the timer as close as possible to cero</h2>
<p id="timer">0000</p>
<button id="stop" onclick="myStopFunction()" >Stop time</button>
<span id="result"></span>
<button id="" onclick="startTimef()" >start</button>
</div>
<script src="main.js"></script>
</body>
</html>
Try this. Removing interval2 from myStopFunction(interval2) will work.
Your first approach will not since you have 2 interval2 variables and JS will use the locally declared interval2 instead of the outer interval2.
var interval2;
function startTimef(){
var startTime = Date.now();
interval2 = setInterval(function() {
var elapsedTime = Date.now() - startTime - 5000;
document.getElementById("timer").innerHTML = (elapsedTime / 1000).toFixed(3);
}, 75);
}
function myStopFunction() {
clearInterval(interval2);
var result = document.getElementById("result");
var score = document.getElementById("timer").textContent;
if (score < -0.200) { result.innerHTML = score+" Almost there ";}
if (score < -500 && score < -0.200) { result.innerHTML = "Almost there";}
if (score > -0.200 && score < 0 ) { result.innerHTML = "No too bad mate";}
if (score > -0.100 && score < 0.200 ) { result.innerHTML = "Perfect !!!";}
if (score > 0.200 ) { result.innerHTML = "You need some work!";}
};
// Press Enter Keyboard
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>TimeOver</title>
</head>
<body>
<div class="main-box">
<h2>Try to Stop the timer as close as possible to cero</h2>
<p id="timer">0000</p>
<button id="stop" onclick="myStopFunction()" >Stop time</button>
<span id="result"></span>
<button id="" onclick="startTimef()" >start</button>
</div>
<script src="main.js"></script>
</body>
</html>

Categories