Search code examples
javascriptjqueryhtmlcontenteditable

Prevent enter from writing new line in content edititable div


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


Solution

  • Instead of keyup, use keydown.

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

    See example on JSFiddle