Last active
February 8, 2023 01:18
-
-
Save drbr/ef65a332daa52786388669eefe506ec7 to your computer and use it in GitHub Desktop.
Bookmarklet to console log the active element on a timer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
javascript: (() => { | |
/* | |
* This script is meant to be run as a JavaScript bookmarklet. "Install" it by pasting the script | |
* into the URL field of a bookmark in your browser. | |
* https://www.freecodecamp.org/news/what-are-bookmarklets/ | |
* | |
* When invoked the first time, it will set a timer that prints the currently focused element to the | |
* console every 2 seconds. When invoked again, it will cancel that timer, and will continue to | |
* toggle the timer on each subsequent invocation. | |
* | |
* This is useful when trying to test keyboard navigation on a webpage, when some elements may not | |
* have visible focus indicators or when the focus order isn't what was expected. | |
* | |
* The script stores the timer on the global variable `window.akInterval` or a different variable | |
* of your choosing. | |
*/ | |
const intervalMillis = 2000; | |
const globalVariableName = 'akInterval'; | |
if (window[globalVariableName]) { | |
const intervalId = window[globalVariableName]; | |
clearInterval(intervalId); | |
delete window[globalVariableName]; | |
console.log(`Stopped activeElement timer (interval ID ${intervalId})`); | |
} else { | |
const intervalId = setInterval( | |
() => console.log(document.activeElement), | |
intervalMillis | |
); | |
window[globalVariableName] = intervalId; | |
console.log( | |
`Started activeElement timer (every ${intervalMillis} ms, interval ID ${intervalId})` | |
); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The timer approach has its advantages, but I just discovered that it's possible to listen to
focus
events so we can actually log the focused element as it changes. See https://hidde.blog/console-logging-the-focused-element-as-it-changes/