Reputation: 4288
Currently I am making an editor using contenteditable. I have the following:
<div contenteditable="true">
<h2>Header</h2>
<p>Content lorem ipsum</p>
</div>
When I create a new using execCommand and then hit enter after it, a < div > is created. However, I want a < p > to be created instead. I can stop the enter from behaving entirely by using the keyup event and returning false (using jQuery), but how to I force the < p > tag over the < div >? (Note, It already places a < p > correctly when I am already inside a < p > tag, but it doesn't work when inside a < div >)
Upvotes: 1
Views: 2682
Reputation: 174
For the upcoming versions of WYMeditor we've solved this issue by completely overriding the the different native implementations (including the enter key handler.)
To force a pargraph (or rather reformat to a paragraph) you can do something like this with jQuery (where element is a DOM Node or a jQuery object):
function formatElement (element, tagName) {
element = $(element);
newElement = $('<'+tagName+'/>').append(element.clone().get(0).childNodes);
element.replaceWith(newElement);
}
This could be done on keyup where you'd get the newly created element by using looking at the current selection and then call the above function.
In WYMeditor we also make sure that we're actually modifying a block element, so that we maintain a valid document structure. If not, we walk up the DOM tree to find a block parent.
Just like DanielH's solution the drawback of this approach is that you need to implement your own undo/redo stack, but as far as I'm aware it's the only reliable cross browser way of doing it.
Upvotes: 2