Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop contentEditable="true" inserting <div> instead of <p> when pressing return?

I have a div

<div contentEditable="true">
    <h1> My headline</h1>
</div>

If i am editing the text inside the <h1> tag, and press return, it adds a new div under, instead of the normal paragraph tag it usually inserts when entering return

Making it:

<div contentEditable="true">
    <h1> My headline edited</h1>
    <div> i tapped return</div>
</div>

What i really want is

<div contentEditable="true">
    <h1> My headline edited</h1>
    <p> i tapped return</p>
    <p> return again</p>
</div>

Whats strange is that usually when you write somewhere and press return it adds a new <p>, but just not when editing <h1>. Is it possible to fix this with Javascript/Jquery/Html5?

I am using Safari on an iOS-device

like image 841
bogen Avatar asked Oct 20 '22 03:10

bogen


1 Answers

Adding a format blocker inside onkeyup with p will force the contenteditable (div) to add <p> tag on return.

editable.onkeyup = (e)=> {
    e = e || window.event
    if (e.keyCode === 13)
        document.execCommand('formatBlock', false, 'p');
}
like image 166
Nilesh Singh Avatar answered Nov 01 '22 14:11

Nilesh Singh