Skip to content

Instantly share code, notes, and snippets.

@drbr
Last active February 8, 2023 01:18
Show Gist options
  • Save drbr/ef65a332daa52786388669eefe506ec7 to your computer and use it in GitHub Desktop.
Save drbr/ef65a332daa52786388669eefe506ec7 to your computer and use it in GitHub Desktop.
Bookmarklet to console log the active element on a timer
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})`
);
}
})();
@drbr
Copy link
Author

drbr commented Feb 8, 2023

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/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment