Contenteditable paragraph tag on enter

Dimitur Vulchanov picture Dimitur Vulchanov · Oct 12, 2011 · Viewed 8.8k times · Source

I was wondering if there is an acceptable way to force all major browsers to insert paragraph tag instead of the default tag that they insert on pressing enter key when contentEditable is true.

As far as I know IE inserts p automatically. But Google Chrome inserts div tag and Firefox inserts br (WTF?!).

Thanks in advance!

Answer

bartaxyz picture bartaxyz · Aug 11, 2013

you can use document.execCommand('formatBlock', false, 'p'); in event like keypress or keydown, etc. to use paragraphs after enter press. For example:

element.addEventListener('keypress', function(ev){
    if(ev.keyCode == '13')
        document.execCommand('formatBlock', false, 'p');
}, false);