I have a div with the attribute contentEditable set.
The trouble I am having is that the first line I type does not get wrapped in tags, but the subsequent lines do.
So typing:
qwerty
zxcv
asdfg
Results in:
<div class="editable" contentEditable="true">
qwerty
<div>zxcv</div>
<div>asdfg</div>
</div>
So I need the qwerty
line to become <div>qwerty</div>
I had issues in Chrome just adding a div. It only worked if your div contains a br tag:
<div class="editable" contentEditable="true">
<div>
<br>
</div>
</div>
@nicholas_r is right, deleting the last character in the editable div will also delete the div added at the beginning. You can avoid this, by catching the last 'backspace'. A simple solution using jquery to do it:
$(".editable").on('keydown', function(event) {
if (event.keyCode === 8 && $(this).html() == '<div><br></div>') {
event.preventDefault();
}
}
If it helps, running the following will let you wrap unwrapped divs . If you trigger it on keypress or something like that, it'll work even if the user removes all content from the div.
$(".editable").contents().filter(function() {
return this.nodeType == 3;
}).wrap('<div></div>');
If you start with an element that contains a div
inside it like this:
<div class="editable" contentEditable="true">
<div></div>
</div>
the first line you type will end up being wraped in a div
.
UPDATE:
This is browser specific. While it did work in most browsers at the time the question was posted, it does not necessarily work anymore in the latest browser version. Best way to tell is to just test it.
I did something like this and it works really well for making sure there's always a div wrapper on the first line of text.
This way if the user clicks into the field and its blank (initial state) it'll put a blank space in, to make sure that their cursor is inside of the new div.
$editable.on('focus', function() {
if ($(this).text().trim() === '') {
console.log('editable is blank, insert a div');
$(this).append($('<div> </div>'));
}
});
You can remove the leading space (if it matters) before saving the data.
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