Prevent contenteditable adding <div> on ENTER - Chrome
Add style display:inline-block;
to contenteditable
, it will not generate div
, p
and span
automatically in Chrome.
Try this:
$('div[contenteditable]').keydown(function(e) {
// trap the return key being pressed
if (e.keyCode === 13) {
// insert 2 br tags (if only one br tag is inserted the cursor won't go to the next line)
document.execCommand('insertHTML', false, '<br/>');
// prevent the default behaviour of return key pressed
return false;
}
});
Click here for demo
You can do this with just a CSS change:
div{
background: skyblue;
padding:10px;
display: inline-block;
}
pre{
white-space: pre-wrap;
background: #EEE;
}
http://jsfiddle.net/ayiem999/HW43Q/
This works in all major browsers (Chrome, Firefox, Safari, Edge)
document.addEventListener('keydown', event => {
if (event.key === 'Enter') {
document.execCommand('insertLineBreak')
event.preventDefault()
}
})
<div class="element" contenteditable="true">Sample text</div>
<p class="element" contenteditable="true">Sample text</p>
There is one inconvenience. After you finish editing, the elements might contain an ending <br>
inside. But you could add code to trim that down if you need to.
Check this answer to remove the trailing <br>
https://stackoverflow.com/a/61237737/670839