Home > Web Front-end > JS Tutorial > How to Insert HTML into a Contenteditable DIV at the Caret Position?

How to Insert HTML into a Contenteditable DIV at the Caret Position?

Mary-Kate Olsen
Release: 2024-11-10 00:19:02
Original
352 people have browsed it

How to Insert HTML into a Contenteditable DIV at the Caret Position?

Inserting HTML into a Contenteditable DIV at the Caret Position

Challenge:

In a contenteditable div, keypress events capture can be used to prevent entering text when the Enter key is pressed. With the cursor in the desired insertion point, we seek a method to insert HTML (e.g., a
tag) without having it displayed as plaintext.

Solution:

While using Range.pasteHTML() works in IE, other browsers display the HTML tag as text. The following function allows us to insert HTML in all major browsers, replacing existing text if selected:

function pasteHtmlAtCaret(html) {
  var sel, range;
  if (window.getSelection) {
    // IE9 and non-IE
    sel = window.getSelection();
    if (sel.getRangeAt && sel.rangeCount) {
      range = sel.getRangeAt(0);
      range.deleteContents();

      // Create a document fragment from the HTML string
      var el = document.createElement("div");
      el.innerHTML = html;
      var frag = document.createDocumentFragment();
      while ((node = el.firstChild)) {
        frag.appendChild(node);
      }

      range.insertNode(frag);

      // Preserve the selection after the inserted content
      if (frag.lastChild) {
        range = range.cloneRange();
        range.setStartAfter(frag.lastChild);
        range.collapse(true);
        sel.removeAllRanges();
        sel.addRange(range);
      }
    }
  } else if (document.selection && document.selection.type != "Control") {
    // IE < 9
    document.selection.createRange().pasteHTML(html);
  }
}
Copy after login

Enhanced Functionality (August 2013):

In response to user requests, an additional parameter has been added to specify whether or not the inserted content should be selected.

function pasteHtmlAtCaret(html, selectPastedContent) {
  // Similar functionality as the original function
  // ...
}
Copy after login

This updated function allows us to control the selection behavior after inserting HTML content.

The above is the detailed content of How to Insert HTML into a Contenteditable DIV at the Caret Position?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template