Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome execCommand 'insertHTML' inserts span outside of node when caret is inside it

My task is to insert an empty span node within a contentEditable div at current caret position.

The following gives me no problems on Firefox 22.0:

HTML

<div class="parent" contentEditable=true>
    <div>text</div>
</div>

Javascript

$('.parent').on("keyup", function(e){
    if (e.which == 73) {
       node = '<span class="new"></span>';
       document.execCommand('insertHtml', null, node);
   }
});

To reproduce: Place caret at some point of the word 'text', then press 'i' key to insert an empty span at current selection.

See: http://jsfiddle.net/amirisnino/pZecx/2/

Example:

When pressing 'i' key in the middle of the word

Expected result:

<div class="parent" contentEditable=true>
    <div>tei<span class="new"></span>xt</div>
</div>

What happens instead?

<div class="parent" contentEditable=true>
    <div>teixt</div>
    <span class="new"></span>
    <div><br></div>
</div>

Any help with this would be greatly appreciated. Thank you in advance.

like image 620
Amiris Niño Avatar asked Jul 09 '13 15:07

Amiris Niño


People also ask

What is execcommand in contentEditable?

When using contentEditable, execCommand () affects the currently active editable element. The Clipboard API can be used instead of execCommand in many cases, but execCommand is still sometimes useful.

What does exec command do in HTML?

Document.execCommand() Jump to: When an HTML document has been switched to designMode, its document object exposes an execCommand method to run commands that manipulate the current editable region, such as form inputs or contentEditable elements.

What is the use of insertion point in HTML?

Inserts the given plain text at the insertion point (deletes selection). Toggles italics on/off for the selection or at the insertion point. (Internet Explorer uses the <em> element instead of <i> .) Centers the selection or insertion point. Justifies the selection or insertion point. Justifies the selection or insertion point to the left.


1 Answers

You can make the contenteditable attribute of span element as false. In order to achieve your expectation, you have to move the last two lines outside of the if-condition. Here it is:

$('.parent').on("keyup", function(e){
    if (e.which == 73) {
         node = '<span contenteditable="false" class="new"></span>';
         document.execCommand('insertHtml', null, node);
       }
       content = $(this).html()
       $('.result').text(content)

});
like image 130
rupali317 Avatar answered Sep 28 '22 04:09

rupali317