-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathscript.js
More file actions
50 lines (40 loc) · 1.72 KB
/
script.js
File metadata and controls
50 lines (40 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
const TOTAL_KEY = "happyButtonTotalClicks";
const CYCLE_KEY = "happyButtonCelebrationClicks";
const CELEBRATION_INTERVAL = 5;
const button = document.getElementById("happy-button");
const clickStatus = document.getElementById("click-status");
const celebrationStatus = document.getElementById("celebration-status");
const celebrationMessage = document.getElementById("celebration-message");
function readStoredCount(key) {
const value = Number.parseInt(window.localStorage.getItem(key) ?? "0", 10);
return Number.isFinite(value) && value >= 0 ? value : 0;
}
let totalClicks = readStoredCount(TOTAL_KEY);
let celebrationClicks = readStoredCount(CYCLE_KEY);
function renderState(showCelebration = false) {
const isGreenButton = totalClicks % 2 === 0;
button.classList.toggle("button-green", isGreenButton);
button.classList.toggle("button-red", !isGreenButton);
document.body.classList.toggle("state-green", isGreenButton);
document.body.classList.toggle("state-red", !isGreenButton);
clickStatus.textContent = `Total clicks: ${totalClicks}`;
celebrationStatus.textContent = `Clicks until celebration: ${
CELEBRATION_INTERVAL - celebrationClicks
}`;
if (showCelebration) {
celebrationMessage.textContent = `Congratulations! You clicked the button ${totalClicks} times.`;
}
celebrationMessage.hidden = !showCelebration;
}
button.addEventListener("click", () => {
totalClicks += 1;
celebrationClicks += 1;
const shouldCelebrate = celebrationClicks === CELEBRATION_INTERVAL;
if (shouldCelebrate) {
celebrationClicks = 0;
}
window.localStorage.setItem(TOTAL_KEY, String(totalClicks));
window.localStorage.setItem(CYCLE_KEY, String(celebrationClicks));
renderState(shouldCelebrate);
});
renderState(false);