wildhaber
wildhaber

Reputation: 1661

Setting contenteditable and overwriting line-breaks to <br /> instead of <div> does not work at the end of the element

I've done a simple script in jsFiddle.net that shows my problem.

I try to overwrite the line breaks in a contenteditable=true element from the default <div> to a <br /> with the following script:

$(".editContents").on("keydown","[contenteditable=true]",function(e) {
    if(e.which===13) {
        lineBreak = "<br />";
        document.execCommand("insertHTML",false,lineBreak);
        return false;
    }
});

It works like it should if you press enter inside the text - but as soon as you try to make a line break at the end of the paragraph nothing happens.

Unfortunately I have no clue whats wrong with it. Any help is warmly welcome :-)

Upvotes: 3

Views: 2794

Answers (1)

ThinkingStiff
ThinkingStiff

Reputation: 65341

It actually is working and inserting a <br /> at the end of the <p>, but whitespace at the end of <p> elements is truncated. You can see this by inspecting the element after you press enter at the end of the paragraph. The problem is, at the end of the <p>, execCommand() is only allowing one to be inserted. Instead of inserting, it seems to be replacing.

It does work if you add another character to '<br />' and insert this instead '<br /> ' (space after the >), but that's probably not what you're looking for because it actually adds an extra space to your <p>.

You may have to check if it's the last character and use insertAdjacentHTML() with beforeEnd instead.

Upvotes: 1

Related Questions