user479947
user479947

Reputation:

Extra linebreak in contenteditable after focus()

In Chrome/Safari with this JSFiddle test http://jsfiddle.net/YLqqE/

If I type 'Hi' and press Enter, the text appears first in the Red box, then moves up to the blue one.

But, if I type 'Hi', click outside of the box to blur() it, then click back on the text and hit Enter, I get an extra space.

Why is that extra space showing up? How can I prevent that from happening?

Upvotes: 2

Views: 127

Answers (2)

orhanhenrik
orhanhenrik

Reputation: 1415

When you press enter, a newline is added to the html of that div. To remove the newline from the div, remove it with a regular expression:
$('#msg').append(newEl.html().replace(/(\r\n|\n|\r)/gm,""));

Fiddle

Upvotes: -1

musicnothing
musicnothing

Reputation: 3985

That's an easy fix. Just return false after a your logic for a return key, so the default action doesn't take place:

http://jsfiddle.net/YLqqE/2/

$(document).keydown(function(e){
    switch(e.keyCode) {
      case 13:
        $('#msg').append(newEl.html());
        newEl.html('')
        return false;
    }
});

Upvotes: 2

Related Questions