Prevent line/paragraph breaks in contentEditable

When using contentEditable in Firefox, is there a way to prevent the user from inserting paragraph or line breaks by pressing enter or shift+enter?


Solution 1:

You can attach an event handler to the keydown or keypress event for the contentEditable field and cancel the event if the keycode identifies itself as enter (or shift+enter).

This will disable enter/shift+enter completely when focus is in the contentEditable field.

If using jQuery, something like:

$("#idContentEditable").keypress(function(e){ return e.which != 13; });

...which will return false and cancel the keypress event on enter.

Solution 2:

This is possible with Vanilla JS, with the same effort:

document.getElementById('idContentEditable').addEventListener('keypress', (evt) => {
    if (evt.which === 13) {
        evt.preventDefault();
    }
});

You should not use jQuery for the most simple things. Also, you may want to use "key" instead of "which": https://developer.mozilla.org/en-US/docs/Web/Events/keypress

Update, since keypress is deprecated:

document.getElementById('idContentEditable').addEventListener('keydown', (evt) => {
    if (evt.keyCode === 13) {
        evt.preventDefault();
    }
});

Solution 3:

Add the following CSS rule to hide line breaks. This is only a style setting, you should add some event handlers to prevent inserting line breaks:

.your_editable br {
    display: none
}

Solution 4:

Other than adding line breaks, the browser adds additional tags and styles (when you paste text, the browser also appends your pasted text style).

The code below covers it all.

  • When you press enter, no line breaks will be added.
  • When you paste text, all elements added by the browser are stripped from the text.

    $('[contenteditable]').on('paste', function(e) {
        //strips elements added to the editable tag when pasting
        var $self = $(this);
        setTimeout(function() {$self.html($self.text());}, 0);
    }).on('keypress', function(e) {
         //ignores enter key
         return e.which != 13;
    });
    

Click here for a live example

Solution 5:

another option is to allow breaks to be entered but remove them on blur. this has the advantage of dealing with pasted content. your users will either love it or hate it (depending on your users).

function handle_blur(evt){
  var elt=evt.target; elt.innerText=elt.innerText.replace(/\n/g,' ');
}

then, in html:

<span onblur="handle_blur(event)" contenteditable>editable text</span>