Search code examples
htmlfirefoxwysiwyg

How to force <br> line break in Firefox ContentEditable


I have a JavaScript WYSIWYG editor (not unlike CKEditor) running on a site.

It has a setting that makes IE create <br> line breaks when you press Enter in the editor.

That works great, but unfortunately, Firefox (I've tested with 5 and 7) will still generate <p> elements, and generate <br> s only if you use Shift + Enter.

Is there a way to make Firefox always generate <br> elements in a contentEditable?


Solution

  • From looking at the standards, it looks like this action is the way it is supposed to be handled. Blocks are broken when no modifier is set on an enter key, and <br>'s are used when shift is pressed. [Source].

    That said, that does not solve your problem, so let's work on that. This line should do

    document.execCommand('insertBrOnReturn', false, true);
    

    Set's it so that when you just hit return, it only puts in a <br> tag. This is only supported by FF, so it shouldn't affect anything on IE. Don't know about other browsers though.

    Note: If the user hits Enter a second time, without typing anything, it creates a new paragraph tag no matter what. To prevent this, you can catch the Enter using the keypress event and stop it, or you could insert in a &nbsp; before you continue with the event (what I'd recommend).

    The tough part for you with this note is checking on the state of the element on keypress. The lazy solution (and the one I would recommend unless it's important to not do this) is to just insert it before every Enter key. If you want to do it the other way, I would check the .innerHTML for the element and see if the last few characters (without trimming the content) are <br/> (so maybe a regex match on /\<br\s?\/?\>$/).