How it works
The value of the counter is stored in a variable:
let currentTotal = 0;
Each click of a button adds or subtracts from the currentTotal. But this isn’t enough to update the display so a function is created which runs with every button click to update the display.
addBtn.addEventListener('click', () => {
currentTotal += 1;
updateCounterDisplay();
});
To do this updateCounterDisplay()
function simply uses:
counterDisplayEl.textContent = currentTotal;
Setting limits
The upper limit for the counter is stored in a variable called limit
:
const limit = 10;
Then an if
statement is used so that if value of currentTotal
is greater than the value of limit
the value of currentTotal
will be equal to the value of limit
. I set the value to 10.
The same is done with the lower limit but instead of a variable being used the lower limit is simply zero. So if the variable currentTotal
is less than zero currentTotal
will be equal to zero.
Changing the background colour
Each time button is clicked the background colour is reset using an hsl value.
The percentage value for luminence is a calculation based on the current counter’s current value, that is the value of the variable currentTotal
divided by the value of limit
(I set this to 10). This is multiplied by 100 to give a percentage value.
So the higher this percentage the brighter the colour
document.body.style.setProperty(
'background-color', `hsl(270, 64%, ${(currentTotal / limit) * 100 }%)`
)
setProperty()
There are several related methods:
removeProperty()
only needs one value eg.removeProperty('background-image')
.getPropertyValue()
again this needs one value eg.getPropertyValue('background-image')
.getPropertyPriority()
determines whether the CSS!important
rule has been applied. This wil eturn eitherimportant
or an empty string.