How can I give keyboard focus to a DIV and attach keyboard event handlers to it?

JavascriptEventsKeyboard

Javascript Problem Overview


I am building an application where I want to be able to click a rectangle represented by a DIV, and then use the keyboard to move that DIV by listing for keyboard events.

Rather than using an event listener for those keyboard events at the document level, can I listen for keyboard events at the DIV level, perhaps by giving it keyboard focus?

Here's a simplified sample to illustrate the problem:

<html>
<head>
</head>
<body>

<div id="outer" style="background-color:#eeeeee;padding:10px">
outer

   <div id="inner" style="background-color:#bbbbbb;width:50%;margin:10px;padding:10px;">
   want to be able to focus this element and pick up keypresses
   </div>
</div>

<script language="Javascript">

function onClick()
{
	document.getElementById('inner').innerHTML="clicked";
	document.getElementById('inner').focus();

}

//this handler is never called
function onKeypressDiv()
{
	document.getElementById('inner').innerHTML="keypress on div";
}

function onKeypressDoc()
{
	document.getElementById('inner').innerHTML="keypress on doc";
}

//install event handlers
document.getElementById('inner').addEventListener("click", onClick, false);
document.getElementById('inner').addEventListener("keypress", onKeypressDiv, false);
document.addEventListener("keypress", onKeypressDoc, false);

</script>

</body>
</html>

On clicking the inner DIV I try to give it focus, but subsequent keyboard events are always picked up at the document level, not my DIV level event listener.

Do I simply need to implement an application-specific notion of keyboard focus?

I should add I only need this to work in Firefox.

Javascript Solutions


Solution 1 - Javascript

Sorted - I added tabindex attribute to the target DIV, which causes it to pick up keyboard events, for example

<div id="inner" tabindex="0">
    this div can now have focus and receive keyboard events
</div>

Information gleaned from http://www.w3.org/WAI/GL/WCAG20/WD-WCAG20-TECHS/SCR29.html

Solution 2 - Javascript

Paul's answer works fine, but you could also use contentEditable, like this...

document.getElementById('inner').contentEditable=true;
document.getElementById('inner').focus();

Might be preferable in some cases.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPaul DixonView Question on Stackoverflow
Solution 1 - JavascriptPaul DixonView Answer on Stackoverflow
Solution 2 - JavascriptPeter BagnallView Answer on Stackoverflow