Anyone is capable of having their caps lock key on at any given time without realizing so. Users can easily spot unwanted caps lock when typing in most inputs, but when using a password
input
, the problem isn’t so obvious. That leads to the user’s password being incorrect, which is an annoyance. Ideally developers could let the user know their caps lock key is activated.
To detect if a user has their keyboard’s caps lock turn on, we’ll employ KeyboardEvent
‘s getModifierState
method:
document.querySelector('input[type=password]').addEventListener('keyup', function (keyboardEvent) { const capsLockOn = keyboardEvent.getModifierState('CapsLock'); if (capsLockOn) { // Warn the user that their caps lock is on? } });
I’d never seen getModifierState
used before, so I explored the W3C documentation to discover other useful values:
dictionary EventModifierInit : UIEventInit { boolean ctrlKey = false; boolean shiftKey = false; boolean altKey = false; boolean metaKey = false; boolean modifierAltGraph = false; boolean modifierCapsLock = false; boolean modifierFn = false; boolean modifierFnLock = false; boolean modifierHyper = false; boolean modifierNumLock = false; boolean modifierScrollLock = false; boolean modifierSuper = false; boolean modifierSymbol = false; boolean modifierSymbolLock = false; };
getModifierState
provides a wealth of insight as to the user’s keyboard during key-centric events. I wish I had known about getModifier
earlier in my career!
Page Visibility API
One event that’s always been lacking within the document is a signal for when the user is looking at a given tab, or another tab. When does the user switch off our site to look at something else? When do they come back?
Modal-Style Text Selection with Fokus
Every once in a while I find a tiny JavaScript library that does something very specific, very well. My latest find, Fokus, is a utility that listens for text selection within the page, and when such an event occurs, shows a beautiful modal dialog in…
Create Twitter-Style Dropdowns Using jQuery
Twitter does some great stuff with JavaScript. What I really appreciate about what they do is that there aren’t any epic JS functionalities — they’re all simple touches. One of those simple touches is the “Login” dropdown on their homepage. I’ve taken…