Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

catch 'enter' press from contenteditable <li> element while typing

Tags:

jquery

I have the following HTML code:

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

When ENTER key is clicked while editing this element, I want to exit editing mode (set contentEditable to false) instead of typing in line break. So I've attached the following event listner:

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

The problem is that the event is not triggered for ENTER key, although it is triggered for all other keys. I don't understand why. The same approach that I'm using was suggested here, but it doens't work for me.

like image 653
Max Koretskyi Avatar asked Aug 17 '13 12:08

Max Koretskyi


People also ask

How do I stop Enter key in Contenteditable?

To prevent contenteditable element from adding div on pressing enter with Chrome and JavaScript, we can listen for the keydown event on the contenteditable element and prevent the default behavior when Enter is pressed. to add a contenteditable div. document. addEventListener("keydown", (event) => { if (event.

What is the HTML attribute Contenteditable used for?

The contenteditable global attribute is an enumerated attribute indicating if the element should be editable by the user. If so, the browser modifies its widget to allow editing.

How do you focus on Contenteditable?

Changing your tabIndex to >= 0 will let you focus on the elements. If you need to do it dynamically, you can just add a tabindex >= 0 to your element in the event listener.

Can I use Contenteditable in react?

Any element can be made editable with the addition of the contenteditable attribute.


2 Answers

You need to bind to keydown, since when keypress has triggered, the event has already occured:

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

Please see the jsFiddle demo

like image 98
BenM Avatar answered Oct 26 '22 22:10

BenM


I already answered a similar question today here. You'll have 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 do not work; as far as I know, keypress only works reliably for alphanumeric characters).

like image 31
Sumurai8 Avatar answered Oct 27 '22 00:10

Sumurai8