Given this HTML code:
<div contenteditable>
....
<span> child-element </span>
....
</div>
When the user clicks on the SPAN element (in order to place the caret inside it), and then presses a character key on the keyboard (in order to edit the text-content of the SPAN element), a keydown
, keypress
, and keyup
event will be fired.
However, the target
property of those corresponding event objects is not the SPAN element, but the DIV element itself.
Live demo: (Also on jsFiddle)
$('div').keydown(function(e) {
alert( e.target.nodeName );
});
div { border:2px solid red; padding:10px; margin:10px; }
span { background-color:yellow; }
<div contenteditable>
BEFORE
<span>SPAN</span>
AFTER
</div>
<p>
Click on the yellow SPAN element (to place the caret inside it), and then press a character key (to change the text-content of the SPAN element). The alert-box shows that the event-target is the DIV element, not the SPAN element...
</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
How can I determine whether or not the key-event occurred inside a SPAN element?