Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

jquery

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.

like image 634
Mohammad Kasiri Avatar asked Dec 25 '22 22:12

Mohammad Kasiri


1 Answers

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>
like image 93
Sumurai8 Avatar answered Apr 08 '23 18:04

Sumurai8