0

I'm trying to add content inside the content box at cursor point using button click & java script function, it's adding inside the box, but if I click somewhere outside & again click the button it's adding content inside the button. How can I restrict the function to add content only in the content div. Below is the HTML & CSS:

var heading = '<span style="color:#0091DA; margin-bottom:30px; font-family:Arial, Helvetica, sans-serif; font-weight: bold; font-size:14px; line-height:120%;">Subheadings in Arial Bold 10.5pt (14px) light blue</span>';

function pasteHtmlAtCaret(html, selectPastedContent) {
  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
      // only relatively recently standardized and is not supported in
      // some 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);
      }
      
      var firstNode = frag.firstChild;
      range.insertNode(frag);

      // Preserve the selection
      if (lastNode) {
        range = range.cloneRange();
        range.setStartAfter(lastNode);
        if (selectPastedContent) {
          range.setStartBefore(firstNode);
        } else {
          range.collapse(true);
        }
        
        sel.removeAllRanges();
        sel.addRange(range);
      }
    }
  } else if ((sel = document.selection) && sel.type != "Control") {
    // IE < 9
    var originalRange = sel.createRange();
    originalRange.collapse(true);
    if (document.getElementById('edit-content')[0].getAttribute("contenteditable", "true")) {
      sel.createRange().pasteHTML(html);
    }
  }
}
.main {
  border: 1px solid #000;
  width: 500px;
  height: 500px;
}

.content {
  border: 1px solid #f00;
  width: 300px;
  height: 100px;
  margin: 180px auto;
  position: relative;
}
<div class="main">
  <div class="content" id="edit-content" contenteditable="true">
    Type your text here
  </div>
</div>

<button class="temp-title" id="add_heading1" onclick="pasteHtmlAtCaret(heading);">Heading</button>
Ben Thomas
  • 3,180
  • 2
  • 20
  • 38
Gourav Roy
  • 25
  • 1
  • 7

0 Answers0