kasiri182 kasiri182 - 1 month ago 9
HTML Question

how to deactive enter event (only enter no shift+enter) in contenteditable

I want to use

contenteditable
attribute in my code but I have one problem.

I want when click (shift + enter) go on next line (point: I want only shift + enter go to next line) and When I click enter key hidden text in this div that has
contenteditable
attribute.

please guide me about it.

Answer

You can use the keydown event for this. Mdn has more information about this event.

With the following example html:

<div id="pinky" contenteditable="true">Pink unicorns are blue</div>

You can attach an keydown event handler to this element. We can then use the event.shiftKey to detect if the shiftKey is pressed together with our enter key. Key 13 is either of the "enter" keys.

$('#pinky').on('keydown', function(e) {
  if (e.which == 13 && e.shiftKey == false) {
    //Prevent insertion of a return
    //You could do other things here, for example
    //focus on the next field
    return false;
  }
});

This snippets shows this in action:

$('#pinky').on('keydown', function(e) {
  if (e.which == 13 && e.shiftKey == false) {
    //Prevent insertion of a return
    //You could do other things here, for example
    //focus on the next field
    return false;
  }
});
#pinky {
  background: pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="pinky" contenteditable="true">Pink unicorns are blue</div>

Comments