Find if a Child Element Has Focus

var hasFocus = !! ($elem.find(':focus').length > 0);

Detecting child focus with focusout jQuery event, setTimeout is required to wait for next element in the DOM to receive focus:

$focusElem.on('focusout', function() {
	var $elem = $(this);
	setTimeout(function() {
		var hasFocus = !! ($elem.find(':focus').length > 0);
		if (! hasFocus) {
			// Handle blur here.
		}
	}, 10);
});

Detecting Keyboard Click Event

When handling a click event, how do you tell if it’s from keyboard enter key or mouse click? Use a keydown event to set up detection before the click event is called:

var ENTER_KEY = 13;
var isKeyEvent = false;

$('.my-elem')
	.on('keydown', myElem_Key)
	.on('click', myElem_Click)
;

var myElem_Key = function(e) {
	var key = e.keyCode || e.which;
	if (key == ENTER_KEY) {
		isKeyEvent = true;
	}
}

var myElem_Click = function(e) {
	if (isKeyEvent) {
		// Handle key event click.
		isKeyEvent = false;
	}
}

The key event can be tied to multiple elements and the callback used as a pass-through for detection.

Keyboard Tabbing to Anchors with jQuery

Working on keyboard accessibility the other day, I found out that an anchor will receive focus if you tab to it but will only trigger a jQuery click event if the anchor has an href attribute.

<a>
	Doesn't work with return/enter key
</a><br />

<a href="#keyboard-click-event">
	It works!
</a><br />

To trigger a click event using keyboard, tab to the element and press return/enter key.