From 2d439dd00ed41c697a917c7445e143ae10ff5e74 Mon Sep 17 00:00:00 2001 From: Ben Harris Date: Sat, 19 Nov 2022 16:30:28 +0000 Subject: [PATCH] js: Move focus-tracking to entirely "focus" events When we disable a button, it loses focus but doesn't generate a "blur" event. This means our "focus-within" class goes wrong. Instead of relying on "blur" events to remove the class, remove it from any inappropriate elements in the "focus" handler. This requires attaching the handler to the root element of the document, but I've got plans that need that anyway. --- emccpre.js | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/emccpre.js b/emccpre.js index b050cf0..f87b576 100644 --- a/emccpre.js +++ b/emccpre.js @@ -525,23 +525,20 @@ function initPuzzle() { command(4); }); - // Event handlers to fake :focus-within on browsers too old for + // Event handler to fake :focus-within on browsers too old for // it (like KaiOS 2.5). Browsers without :focus-within are also - // too old for focusin/out events, so we have to use focus and + // too old for focusin/out events, so we have to use focus events // which don't bubble but can be captured. - menuform.addEventListener("focus", function(event) { - var elem = event.target; - while (elem && elem !== menuform) { + // + // A button losing focus because it was disabled doesn't generate + // a blur event, so we do this entirely in the focus handler. + document.documentElement.addEventListener("focus", function(event) { + for (var elem = event.target; elem; elem = elem.parentElement) elem.classList.add("focus-within"); - elem = elem.parentElement; - } - }, true); - menuform.addEventListener("blur", function(event) { - var elem = event.target; - while (elem && !elem.contains(event.relatedTarget)) { - elem.classList.remove("focus-within"); - elem = elem.parentElement; - } + for (elem of + Array.from(document.getElementsByClassName("focus-within"))) + if (!elem.contains(event.target)) + elem.classList.remove("focus-within"); }, true); // Set up the function pointers we haven't already grabbed.