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.
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.
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.
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.
Any element can be made editable with the addition of the contenteditable attribute.
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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With