Mattias
Mattias

Reputation: 3169

How to call onkeydown/onfocus to a list tag?

I have a list, and within this list im trying to call a function when keyisdown/onfocus/etc? This wont trigger the function:

 <li onkeydown="myFunction()"></li>

The normal onclick works fine(calling the function when the "click is going up") and will trigger the function:

<li onclick="andrafarg()"></li>

So my question is: How can i call this function when the list is clicked immediately down?

Upvotes: 2

Views: 5301

Answers (1)

empiric
empiric

Reputation: 7878

From the jQuery docs:

The keydown event is sent to an element when the user first presses a key on the keyboard. 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.

So as li elements can't get focused, the keydown-event will never be triggered. For a reference for focusable elements, you might have a look at this answer.

But because of the event-bubbling, an input-field inside the list will trigger the keydown-event, if the event-listener is registered on the input itself or a parent-element. Example:

HTML

<ul>
    <li><input type="text" /></li>
</ul>

Javascript

$('ul > li').on('keydown', function(){
   alert('Event triggered'); 
});

Demo

Upvotes: 6

Related Questions