Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

avoid ie contentEditable element to create paragraphs on Enter key

On InternetExplorer, a contentEditable DIV creates a new paragraph (<p></p>) each time you press Enter whereas Firefox creates a <br/> tag. Is it possible to force IE to insert a <br/> instead of a new paragraph ?

like image 979
Franck Freiburger Avatar asked Jan 13 '10 15:01

Franck Freiburger


1 Answers

Here's a solution (uses jQuery). After you click on the 'Change to BR' button, the <br> tag will be inserted instead of the <p></p> tag.

Html:

<div id='editable' contentEditable="true">
This is a division that is content editable. You can position the cursor 
within the text, move the cursor with the arrow keys, and use the keyboard 
to enter or delete text at the cursor position.
</div>
<button type="button" onclick='InsertBR()'>Change to BR</button>
<button type="button" onclick='ViewSource()'>View Div source</button>

Javascript:

function InsertBR()
{
    $("#editable").keypress(function(e) {
        if (e.which == 13) 
        {
            e.preventDefault();
            document.selection.createRange().pasteHTML("<br/>")     
        }
    });
}

function ViewSource()
{           
    var div = document.getElementById('editable');
    alert('div.innerHTML = ' + div.innerHTML);
}

These links helped. Working example here.

like image 79
rosscj2533 Avatar answered Oct 02 '22 23:10

rosscj2533