Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger ENTER event in contentEditable

I have a contenteditable div and would like to trigger an 'enter' when certain keys (like D) are pressed. Below code doesn't work...

$('#div_edit').keydown(function(e) {
    if(e.keyCode == 68) {
        var k = jQuery.Event('keypress', { which: 13 });
        $('#div_edit').trigger(k);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="div_edit" contenteditable="true"></div>

I'm only concerned about Chrome.

EDIT: I would like to add that everytime the D key is pushed, it creates a new element 'div' inside the contenteditable where the user can continue typing in the new div/new line. Example:

<div id="div_edit" contenteditable="true">
    <div>The start of the sentence</div>
    <div>user hit D so continue typing here</div>
</div>

EDIT: I guess my main question is, is there no way to trigger an ENTER in a contenteditable element???

like image 952
kko Avatar asked Jul 26 '26 00:07

kko


1 Answers

Hope this brings you closer to what you are trying to do:

// function from http://stackoverflow.com/questions/4834793/set-caret-position-right-after-the-inserted-element-in-a-contenteditable-div/4836809#4836809
function insertNodeAtCaret(node) {
  if (typeof window.getSelection != "undefined") {
    var sel = window.getSelection();
    if (sel.rangeCount) {
      var range = sel.getRangeAt(0);
      range.collapse(false);
      range.insertNode(node);
      range = range.cloneRange();
      range.selectNodeContents(node);
      range.collapse(false);
      sel.removeAllRanges();
      sel.addRange(range);
    }
  } else if (typeof document.selection != "undefined" && document.selection.type != "Control") {
    var html = (node.nodeType == 1) ? node.outerHTML : node.data;
    var id = "marker_" + ("" + Math.random()).slice(2);
    html += '<span id="' + id + '"></span>';
    var textRange = document.selection.createRange();
    textRange.collapse(false);
    textRange.pasteHTML(html);
    var markerSpan = document.getElementById(id);
    textRange.moveToElementText(markerSpan);
    textRange.select();
    markerSpan.parentNode.removeChild(markerSpan);
  }
}
$('#div_edit').keydown(function(e) {
  if (e.keyCode == 68) {
    insertNodeAtCaret(document.createElement("br"));
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="div_edit" contenteditable="true"></div>
like image 128
Samuel Liew Avatar answered Jul 27 '26 18:07

Samuel Liew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!