Insert Content in Cursor position using jquery

21 May

HTML Content:

<input type="button" value="Paste HTML" onclick="document.getElementById('contDiv').focus(); pasteHtmlAtCaret('<b>INSERTED</b>'); "> 

<div id="contDiv" contenteditable="true">  
Place to Past Content

Javascript method to print the content in cursor position:

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.createContextualFragment() would be useful here but is
      // non-standard and not supported in all browsers (IE9, for one)
      var el = document.createElement("div");
      el.innerHTML = html;
      var frag = document.createDocumentFragment(), node, lastNode;
      while ( (node = el.firstChild) ) {
        lastNode = frag.appendChild(node);
      // Preserve the selection
      if (lastNode) {
        range = range.cloneRange();
   } else if (document.selection && document.selection.type != "Control") {
     // IE < 9




Leave a comment

Posted by on May 21, 2014 in jquery


Tags: ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: