contentEditable - Firefox <br /> tag

Shaokan picture Shaokan · Apr 18, 2011 · Viewed 8.8k times · Source

Firefox inserts a <br /> tag on press enter whereas the other browsers are adding either a <p> or <div>. I know that chrome and safari are inserting the same tag of the firstchild of the contentEditable div. So do Firefox, however, if the first tag's innerHTML is empty firefox is just ignoring the tag and creating a new line by pushing the default node in the second line and writes directly inside the editor instead of inside a child node. So basically, I want Firefox to write inside the given tag and continue to insert that kind of node on each press on enter. How can it be done? Any suggestions?

Answer

Shaokan picture Shaokan · Apr 19, 2011

I've found the solution :) In order to make this work, you've to give an id to the caret's parent element. Then you can use the following code. Please note that I get the browsernName from c# and put it into a hidden field. That's why I equaled it to "firefox". The following code is tested with FF 3.6 and it works perfectly. The only thing is that you'll have to check the caret's parent element and if it is not equal to the current row's id, then you'll have to place the caret inside the current row by using a selection function. Also, perform this code on the keyup event and make sure that if you perform some other codes on the keyup event, put this code at the end of it! Anways, enjoy :)

// The code works good in the following cases:
// 1) If there is text inside the editor and the user selects the whole text
//    and replace it with a single character, the <p> tag will be placed and the
//    text will place inside the p tag
// 2) If the user selects the whole code and deletes it and begins to type again
// 3) If the user types normally and press enter 
// NB: Please note me if you find any bug

if (browserName == "firefox") {
    //remove all br tags
    var brs = txteditor.getElementsByTagName("br");
    for (var i = 0; i < brs.length; i++) { brs[i].parentNode.removeChild(brs[i]); }
    //check whether there is a p tag inside
    var para = txteditor.getElementsByTagName("p");
    if (para.length == 0) {
        var inner = txteditor.innerHTML.replace(/^\s+|\s+$/g, '');
        var str = (inner == "") ? "&#8203;" : txteditor.innerHTML;
        var nText = "<p id=\"" + cRow + "\">" + str + "</p>";
        // in order to prevent a dublicate row clear inside the text editor
        txteditor.innerHTML = "";
        document.execCommand('insertHTML', false, nText);
    } else {
        // always make sure that the current row's innerHTML is never empty
        if (document.getElementById(cRow).innerHTML == "")
            document.getElementById(cRow).innerHTML = "&#8203;";
    }
}