Skip to content

Commit

Permalink
Replace keyup event listener with timeouts
Browse files Browse the repository at this point in the history
This change fixes a UI bug that caused some keys to keep their
hover style after key-up. This bug can be observed when typing
key chords such as [Shift] + [8] (i.e. asterisk character): if
[Shift] is released before [8], the hover style remains.
  • Loading branch information
pricebenjamin committed Feb 25, 2024
1 parent 4652ad4 commit d913baf
Showing 1 changed file with 10 additions and 5 deletions.
15 changes: 10 additions & 5 deletions 005-calculator/sources.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ document.addEventListener('DOMContentLoaded', () => {
appRoot.addEventListener('click', clickHandler);
document.addEventListener('keydown', keyboardHandler);
document.addEventListener('keydown', simulateHover);
document.addEventListener('keyup', simulateHover);

function clickHandler(event) {
const target = event.target;
Expand All @@ -24,14 +23,20 @@ document.addEventListener('DOMContentLoaded', () => {
btn.click();
}

const buttonTimers = {};
const SIMULATED_HOVER_DELAY_MS = 100;

function simulateHover(event) {
const btn = buttonFilter(event);
if (!btn) return;
if (event.type == 'keydown') {
btn.classList.add('hover');
} else if (event.type == 'keyup') {
btn.classList.remove('hover');

btn.classList.add('hover');
if (buttonTimers[event.key]) {
clearTimeout(buttonTimers[event.key]);
}
buttonTimers[event.key] = setTimeout(() => {
btn.classList.remove('hover');
}, SIMULATED_HOVER_DELAY_MS);
}

function buttonFilter(event) {
Expand Down

0 comments on commit d913baf

Please sign in to comment.