Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Contenteditable adds a <br> when I hit space

Tags:

I'm not sure why, but if you have an element with contenteditable enabled, the first time you enter a space, it'll append a <br> tag into the element. If the element has a space in it by default (<p contenteditable="true">this is a test</p>), it'll be fine, but as soon as the user hits that spacebar (or even copy+pastes a space character), Firefox adds a <br _moz_dirty="" /> to the <p>.

Does anyone have any idea why or a simple fix? This is my first time playing with contenteditable, so a lot of this is new to me. At the moment, I'm just using $('br').remove() which seems to be working, but I'd love an explanation and a proper way to prevent it if anyone knows.

like image 456
Jordan Avatar asked Oct 27 '10 23:10

Jordan


2 Answers

I encountered this today and also don't know why Firefox does it. I've dealt with it like this.

function zapTrailingLinebreak (editableNode) {
    let children = Array.from(editableNode.childNodes)

    children.forEach(child => {
        if (children.indexOf(child) == children.length - 1) {
            if (child.tagName && child.tagName === "BR") {
                editableNode.removeChild(child)
            }
        } 
    })
}
like image 84
Scott Martin Avatar answered Nov 06 '22 10:11

Scott Martin


You can remove extra BR tag at end by this

let lastTag = document.querySelector('#yourDiv').lastElementChild;
if(lastTag && lastTag.tagName == "BR") lastTag.remove();
like image 24
Airy Avatar answered Nov 06 '22 09:11

Airy