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.