views:

519

answers:

1

I have a div who's contenteditable property has been set to true.How do I get the children to respond to keyboard events? Seems like the only way is to capture the events in the parent div and figure out the child via the selection apis. Is there a better way? More specifically, can I attach a keyboard event handler to child elements? Am I missing something?

Attached is sample code that illustrates the problem. Hope the in-code comments are sufficiently explanatory.

<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>

<BODY>
<div id="editable" contentEditable='true' style='height: 130px; width: 400px; border-style:solid; border-width:1px'>
    <span id="span1" onkeypress="alert('span1 keypress')">test text 1</span> <!-- does not work -->
    <span id="span2" > test text2</span>
    <span id="span3" onclick="alert('span3 clicked')">test text 3</span>  <!-- this works fine -->
</div>
<!-- Uncomment this to set a keypress handler for span2 programatically. still doesnt work -->
<!--
<script type="text/javascript">
    var span2 = document.getElementById('span2');
    span2.onkeypress=function() {alert('keypressed on ='+this.id)};
</script>
-->

<!-- Uncomment this to enable keyboard events for the whole div. Finding the actual child that the event is happening on requires using the selection api -->
<!--
<script type="text/javascript">
    var editable = document.getElementById('editable');
    editable.onkeypress=function() {alert('key pressed on ='+this.id+';selnode='+getSelection().anchorNode.parentNode.id+',offset='+getSelection().getRangeAt(0).startOffset)};
</script>
-->
</BODY>
</HTML>
+2  A: 

It's because regular spans and divs are incapable of receiving focus. You can make a normal span or div focusable by adding a tabindex attribute to the tag, or by making it editable. You don't want a tabindex on the child span because this seems to prevent it being editable in IE. I was going to suggest examining the target / srcElement properties of the Event object passed to the keypress handler for the whole div but in IE this only gives you a reference to the same div rather than the child span. So in answer to your question, I don't believe there is a better cross-browser solution than using the selection to check where the character was typed.

Tim Down