-1

How can I prevent the user from writing a new line with the enter key in a contenteditable div?

So far I have tried (the id of my editable div is editable:

$('#editable').on('keyup', function(e) {
    if (e.which == 13) {
        event.preventDefault();
    }
});

However this does not work.

Is this possible using JS and jQuery?

Edit

I have been informed that pressing enter does not insert a new line so I have put a picture showing when happens when I press enter inside the editable div.

I would like code to remain on one line basically, even if the user presses enter.

Image

Alex Hawking
  • 1,125
  • 5
  • 19
  • 35
  • 1
    ENTER doesn't create a new-line into a contenteditable div element. It creates `
    ` or `p` element, depending on the implementation, and the value of `execCommand('defaultParagraphSeparator')` if set.
    – Teemu Mar 21 '20 at 10:10

1 Answers1

1

Instead of keyup, use keydown.

const ediatble = document.querySelector('#editable');
ediatble.addEventListener('keydown', e => {
  if (e.key === 'Enter') {
    e.preventDefault();

  }
});

See example on JSFiddle

Ragland Asir
  • 68
  • 2
  • 6