I use Google Chrome.
I need to have a very tiny HTML editor and I found Simple Edit. Very small editor, just for my needs. However... This and many other editors that are using Content Editable have one common problem.
Problem
After creating a list (hit enter twice on last list item), it creates a new div. Expected to me would be to create a new paragraph tag.
Links
Question
What is the correct way of prevent divs, and instead add paragraph tags after a list?
All you have to do is set the contenteditable attribute on nearly any HTML element to make it editable.
To edit the content in HTML, we will use contenteditable attribute. The contenteditable is used to specify whether the element's content is editable by the user or not. This attribute has two values. true: If the value of the contenteditable attribute is set to true then the element is editable.
The contenteditable global attribute is an enumerated attribute indicating if the element should be editable by the user. If so, the browser modifies its widget to allow editing.
The contenteditable attribute specifies whether the content of an element is editable or not. Note: When the contenteditable attribute is not set on an element, the element will inherit it from its parent.
The answer posted by Bryan Allo did not take into account that you need to place the cursor at the end of the div. Otherwise upon every replace action the user would have to hit CTRL-End.
This is the solution I propose, also to be seen in action at http://jsfiddle.net/82dS6/:
function setEndOfContenteditable(contentEditableElement){
// Taken from http://stackoverflow.com/a/3866442/1601088
var range,selection;
if(document.createRange){//Firefox, Chrome, Opera, Safari, IE 9+
range = document.createRange();
range.selectNodeContents(contentEditableElement);
range.collapse(false);
selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
else if(document.selection){//IE 8 and lower
range = document.body.createTextRange();
range.moveToElementText(contentEditableElement);
range.collapse(false);
range.select();
}
}
function replaceDivWithP(el){
$(el).find('div').each(function(){
$(this).replaceWith($('<p>' + $(this).html() + '</p>'));
});
}
$(function(){
$(".text").simpleEdit();
});
$('.textarea').bind('keyup', function(){
replaceDivWithP(this);
setEndOfContenteditable(this);
});
Instead of processing on-the-fly with every keyup
event, you could consider post-processing:
$('.textarea').bind('blur', function(){
$('.textarea div').contents().unwrap().wrap('<p/>');
});
Fiddle: http://jsfiddle.net/thNUS/4/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With