Caps Lock Detection/Prevention

October 17, 2020
By

If you’ve ever had a problem with people on the internet always YELLING into your form inputs then this snippet might be for you.

function preventCapsLockInterference(e) {
	if (e.ctrlKey || !/^[A-Z]$/i.test(e.key)) {
		return;
	}

	var isCapsLetter = /[A-Z]/.test(e.key),
		capsLockOn = e.shiftKey != isCapsLetter,
		el = e.target;

	if (capsLockOn) {
		e.preventDefault();

		var start = el.selectionStart,
			end = el.selectionEnd,
			char = isCapsLetter ? e.key.toLowerCase() : e.key.toUpperCase();

		el.value = el.value.substr(0, start) + char + el.value.substr(end);
		el.selectionStart = el.selectionEnd = start + 1;
	}

	if (!el.hasOwnProperty('__capsLockOn') || el.__capsLockOn != capsLockOn) {
		el.__capsLockOn = capsLockOn;
		el.dispatchEvent(new CustomEvent('caps-lock', {detail: capsLockOn}));
	}
}

You can bind it to your inputs by passing the function name in directly to any keydown events as such: input.addEventListener('keydown', preventCapsLockInterference, false) or with jQuery $input.on('keydown', preventCapsLockInterference). Additionally, when the user begins typing, a custom event called caps-lock will be emitted onto the element, the detail propery of which will describe if the caps lock key is on. This will happen at most once each time the user types after having toggled the caps lock key.

input.addEventListener('caps-lock', function(e) {
	if (e.detail) {
		alert('You have caps lock on');
	}
});