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)
` – Renan Protector Nov 19 '13 at 21:31