Key Code not Returned for "e.which"

I trying to get the key code after a div is clicked. I set my function to be able to interpret mouse and keyboard events. However, I keep getting the number “1” on keydown. Here’s my code:

$(".game_toolbox_slot").on("click keydown", function (e) {
		console.log(e.which);
});

Hi @steveclynn

This is what the Jquery documentation says about the keydown event.

It can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for this event type.

Though I am not sure, looks like the event handler is triggered for the click event and the 1 is due to the mouse click.

Try changing the div to a focusable element like button or input element and press any key.

I ran a quick test an added tabindex=“0” to my div. I simplified my code to:

$("#mydiv").keypress(function(){
console.log(11111);
});

But still nothing happens. I swear I’ve been able to add keyboard events to a div in the past just as long as I added a tabindex to the div.

Has something changed or am I remembering thins incorrectly?

Also, for my design a div works best instead of using a focusable element like button or input.

Well, if you make the div focusable by setting the tabindex attribute to 0, then it will work. The event handler will be triggered if the div is in focus.