Prevent line/paragraph breaks in contentEditable

Viewed 52268

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?

11 Answers

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.

Add:

display: flex;

On the contenteditable html element

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

Solution proposed by Kamens doesn't work in Opera, you should attach event to document instead.

/**
 * Pass false to enable
 */
var disableEnterKey = function(){
    var disabled = false;

    // Keypress event doesn't get fired when assigned to element in Opera
    $(document).keypress(function(e){
        if (disabled) return e.which != 13;
    });                 

    return function(flag){
        disabled = (flag !== undefined) ? flag : true;
    }
}();    

I came here searching for the same answer, and was surprised to find it's a rather simple solution, using the tried and true Event.preventDefault()

const input = document.getElementById('input');

input.addEventListener('keypress', (e) => {
  if (e.which === 13) e.preventDefault();
});
<div contenteditable="true" id="input">
  You can edit me, just click on me and start typing.
  However, you can't add any line breaks by pressing enter.
</div>

Use CSS:

word-break: break-all;

For me, its worked!

Related