Explain Codes LogoExplain Codes Logo

Prevent contenteditable adding `` on ENTER - Chrome

javascript
prompt-engineering
contenteditable
preventdefault
Alex KataevbyAlex Kataev·Jan 12, 2025
TLDR

Here's the quick save! Stop those unwelcomed <div> tags in contenteditable on an Enter press by intercepting the event with JavaScript:

document.addEventListener('keydown', function(e) { if (e.key === 'Enter' && !e.shiftKey) { // because Shift+Enter = new paragraph, remember? document.execCommand('insertLineBreak'); // swapping div for br, hurray! e.preventDefault(); // No more div, thanks! } });

Poof! The creation of those unnecessary <div> tags on an Enter press is now replaced with insertLineBreak. Coding is magic!

Smoothing the user experience

Align the behavior of contenteditable with user expectations by redefining Enter's function. The default behavior varies across browsers, but we can control it, here's how.

Insert <br> not blocks

Prevent block creation on a new line:

document.execCommand('insertHTML', false, '<br><br>');

Running insertHTML instead of insertLineBreak, inserts two <br> tags, creating a double line-break. Just like you hit Enter twice, but no block element.

Stopping the default behavior

Interrupt the insertion of unwanted elements:

if (e.key === 'Enter') { e.preventDefault(); // Behold the power of preventDefault. div, be gone! }

By calling event.preventDefault(), the Enter key inserts a new line instead of triggering its default behavior.

Applying CSS styles

To alter the behavior of contenteditable, we can use some spells from our CSS wizardry:

Using Inline-block

To prevent the automatic creation of certain tags, make use of your style sheet:

[contenteditable] { display: inline-block; /* Because inline-block is your friend in these trying div times! */ }

Wrestling with white spaces

Here's how we can respect the spaces and line breaks with CSS:

[contenteditable] { white-space: pre-wrap; /* Wrapping break and white spaces like a gift */ }

Cursor control and ending the <br> trail

By handling the selection range with window.getSelection(), we can accurately place the cursor. Meanwhile, trailing <br> tags can be trimmed with JavaScript to maintain tidiness.

Compatibility checks and special cases

Chrome might be our focus, but all browsers deserve our love! Plus, a few extra insights on DOM operations and CSS:

Cross-browser compatibility

Testing your solution across major browsers including Firefox, Safari, and Edge is a must. These browsers might have a slightly different take on contenteditable.

Playing with DocumentFragment & Range

Advanced DOM-manipulation tools like document.createDocumentFragment()and range.deleteContents() paired with range.insertNode(), allow precise pointers for new content.

Finessing containers

CSS properties like background, margin, and padding help cater your contenteditable element to the dynamics of its parent container.