Skip to content Skip to sidebar Skip to footer

How To Detect When A Child-element Of A Contenteditable Div Is Edited Via Keyboard?

Given this HTML code:
.... child-element ....
When the user clicks on the SPAN element (in order to

Solution 1:

This can be done using the selection APIs:

$('div').keydown(function(e) {
    if (document.selection) {
        alert(document.selection.createRange().parentElement().tagName); // IE
    } else {
        // everyone elsealert(window.getSelection().anchorNode.parentNode.tagName); 
    }
});

Note: The above example is simplistic. See the SO post linked below for a complete solution to the selection problem.

Demo (also on jsFiddle):

$('div').keydown(function(e) {
    if (document.selection)
        alert(document.selection.createRange().parentElement().tagName); // IEelsealert(window.getSelection().anchorNode.parentNode.tagName); // everyone else
});
div { border:2px solid red; padding:10px; margin:10px; }
span { background-color:yellow; }
<divcontenteditable>
    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><divid="stuff"/><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

References:

Solution 2:

Making the whole div editable means that <span> tag is nothing but text content. If you just want the span to be editable, set contentEditable on the span itself.

Post a Comment for "How To Detect When A Child-element Of A Contenteditable Div Is Edited Via Keyboard?"