Renan  Protector
Renan Protector

Reputation: 183

How to implement break lines and paragraphs on contenteditable?

I’m building a simple text editor for Safari only. I need to implement a very specific behavior:

First enter - Creates <br> tag

Second enter (after <br>) - Create new paragraph

I’m already listening for enter on keypress event and using formatBlock to format paragraphs. How can I check if element before caret is a <br> element, so I can use formatBlock?

By default, Safari adds <div><br></div> on enter keypress, so I need to use preventDefault for first enter too. (code above)

I create new paragraphs using:

$("#content").live("keypress", function(e){
    if (e.which == 13) {
        document.execCommand("formatBlock", false, "p"); 
    }
});

I can add br's using: ( Make a <br> instead of <div></div> by pressing Enter on a contenteditable )

if (window.getSelection) {          
    var selection = window.getSelection(),              
        range = selection.getRangeAt(0),              
        br = document.createElement("br");          
    range.deleteContents();          
    range.insertNode(br);
    range.setStartAfter(br);
    range.setEndAfter(br);
    range.collapse(false);
    selection.removeAllRanges();
    selection.addRange(range);
    return false; 
}

UPDATE: User is typing a paragraph like this: <p>This is my paragraph</p>. At enter keypress, code should be <p>This is my paragraph<br></p> (cursor after br). Pressing enter for second time should result on <p>This is my paragraph</p><p></p> (cursor on second paragraph)

Upvotes: 2

Views: 1570

Answers (2)

Chandranshu
Chandranshu

Reputation: 3669

DISCLAIMER: This is tested only on Chromium.

var sel = window.getSelection();
var range = sel.getRangeAt(0);
if ((sel.extentNode.previousElementSibling instanceof HTMLBRElement)
     && range.startOffset == 0)
{
     // Do your magic to start a paragraph.
} else {
     // Your existing code to add a <br> element since there is no <br> before it.
}

Upvotes: 1

bren
bren

Reputation: 4334

You could use keydown, for example:

<div id="textarea"></div>

Then in your script file:

document.getElementById("textarea").addEventListener("keydown",function(e){if(e.keyCode == 32) {ocument.getElementById("textarea").innerHTML+="<br />"} })

And your other stuff

Upvotes: 1

Related Questions