RSS

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
</div>

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.deleteContents();
    
      // 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);
      }
      range.insertNode(frag);
   
      // Preserve the selection
      if (lastNode) {
        range = range.cloneRange();
        range.setStartAfter(lastNode);
        range.collapse(true);
        sel.removeAllRanges();
        sel.addRange(range);
      }
    }
   } else if (document.selection && document.selection.type != "Control") {
     // IE < 9
     document.selection.createRange().pasteHTML(html);
   }
}

 

 

 

 
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:

WordPress.com Logo

You are commenting using your WordPress.com 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: