Catch 'enter' click from contenteditable <li> element while typing

I have the following HTML code:

<li class="option-item new" contenteditable="true">simple element2</li> 

When the ENTER key is pressed while editing this item, I want to exit edit mode (set contentEditable to false) instead of entering a line. So I added the following list of events:

 $("#ctx-options").on('keypress', '.option-item.new', catch_enter); 

The problem is that the event does not fire for the ENTER key, although it fires for all the other keys. I do not understand why. The same approach I used was suggested here , but it does not work for me.

+4
source share
2 answers

I already answered a similar question here today. You will need to use the keydown event. keypress will only work for a limited subset of keys (the return key seems to work for me, but the arrow keys don't work, as far as I know, pressing a key only works for alphanumeric characters).

+3
source

You need to bind to keydown , since when keypress triggered keypress event already happened:

 $("#ctx-options").on('keydown', '.option-item.new', function(e) { if(e.keyCode == 13) { e.preventDefault(); } }); 

Please view jsFiddle demo

+4
source

Source: https://habr.com/ru/post/1497580/


All Articles