Skip to content

Commit a2b57bc

Browse files
committed
Add pause on hover for toast progress bar
Introduces functionality to pause the toast progress bar when the user hovers over the toast, resuming when the mouse leaves. Refactors progress tracking to support pausing and ensures the toast hides only after the full duration has elapsed.
1 parent f149b39 commit a2b57bc

File tree

1 file changed

+24
-13
lines changed

1 file changed

+24
-13
lines changed

scripts/script.js

Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -69,14 +69,14 @@ document.addEventListener("DOMContentLoaded", function () {
6969
const closeBtn = document.getElementById('toastClose');
7070

7171
let progressInterval;
72+
let elapsedTime = 0;
73+
let lastTick = 0;
74+
let isPaused = false;
7275

7376
function showToast() {
7477
// Check if toast has been shown before
7578
const hasShown = localStorage.getItem(STORAGE_KEY);
76-
77-
if (hasShown) {
78-
return; // Don't show if already shown
79-
}
79+
if (hasShown) return;
8080

8181
// Mark as shown
8282
localStorage.setItem(STORAGE_KEY, 'true');
@@ -90,29 +90,40 @@ document.addEventListener("DOMContentLoaded", function () {
9090

9191
function hideToast() {
9292
toast.classList.remove('show');
93-
if (progressInterval) {
94-
clearInterval(progressInterval);
95-
}
93+
clearInterval(progressInterval);
9694
}
9795

9896
function startProgress() {
99-
const startTime = Date.now();
97+
lastTick = Date.now();
10098

10199
progressInterval = setInterval(() => {
102-
const elapsed = Date.now() - startTime;
103-
const remaining = Math.max(0, 100 - (elapsed / TOAST_DURATION) * 100);
100+
if (isPaused) return;
101+
102+
const now = Date.now();
103+
elapsedTime += now - lastTick;
104+
lastTick = now;
105+
106+
const remaining = Math.max(0, 100 - (elapsedTime / TOAST_DURATION) * 100);
104107

105108
progressBar.style.width = remaining + '%';
106109

107-
if (remaining === 0) {
110+
if (elapsedTime >= TOAST_DURATION) {
108111
hideToast();
109112
}
110113
}, 50);
111114
}
112115

113-
// Close button handler
116+
// Hover pause
117+
toast.addEventListener('mouseenter', () => {
118+
isPaused = true;
119+
});
120+
121+
toast.addEventListener('mouseleave', () => {
122+
isPaused = false;
123+
lastTick = Date.now();
124+
});
125+
114126
closeBtn.addEventListener('click', hideToast);
115127

116-
// Initialize toast
117128
showToast();
118129
})();

0 commit comments

Comments
 (0)