I made this code that increments a number with a button. I would like to add a condition when the number reaches a defined value, in order to display a text. Thanks for the help.
My code:
const incrementCount = document.getElementById("btn");
const totalCount = document.getElementById("compteur");
var count = 0;
totalCount.innerHTML = count;
const handleIncrement = () => {
count ;
totalCount.innerHTML = count;
};
incrementCount.addEventListener("click", handleIncrement);
<div id="compteur"></div>
<div id="btn" ontouchstart ontouchend></div>
CodePudding user response:
Just have a maxCount
variable and compare the new count to the max after each iteration. Once the max is reached, a message will display.
In the example below, the count will keep going. The alert
is wrapped in a setTimeout
so that the count can be updated to 10
, before the alert dialog is displayed.
const
incrCountBtn = document.querySelector('#btn'),
totalCountEl = document.querySelector('#compteur'),
maxCount = 10,
message = 'You have reached the limit';
let count = 0;
totalCountEl.innerText = count;
const handleIncrement = () => {
count = 1;
totalCountEl.innerText = count;
if (count === maxCount) {
setTimeout(() => {
alert(message);
}, 100);
}
};
incrCountBtn.addEventListener('click', handleIncrement);
<div id="compteur"></div>
<button type="button" id="btn" ontouchstart ontouchend>Increment</button>