1

I have this almost good piece of code. Almost because IE 11 breaks it:

.textarea {
    text-align: left;
    background: white;
    border: 1px solid grey;
    border-style: inset;
    height: 150px;
    overflow-y: auto;
    word-wrap: break-word;
    width: 400px;
}
<div class='textarea' contenteditable='true' id='sec1'>blabla</div>

Why does the text (first line) move down after I hit return? I want either the text to appear at first where it will drop to, or just stay there. This will happen even if the 'first line' is entered manually, with no initial content.

kabanus
  • 24,623
  • 6
  • 41
  • 74
  • I can't see anything wrong with this, everything works for me... In which place do you click to focus on div? – Wilkoklak Jan 04 '17 at 19:02
  • I'm not able to reproduce your issue. The text does not move when I hit return. Or am I misunderstanding your issue? – Kuja Jan 04 '17 at 19:02
  • @Wilkoklak figured the mismatch - this only happens on I.e.11. I'll update the post and tags. – kabanus Jan 04 '17 at 19:03
  • It seems like in IE 11 the text gets converted to a `

    ` element. The reason why it drops a little is because of margins.

    – dokgu Jan 04 '17 at 19:12

1 Answers1

1

This happens because IE adds p when you press enter. Using Shift + Enter will enter a br like the rest of the browsers.

Alternatively you could style the p elements in there to not have top margin

.textarea {
    text-align: left;
    background: white;
    border: 1px solid grey;
    border-style: inset;
    height: 150px;
    overflow-y: auto;
    word-wrap: break-word;
    width: 400px;
}

.textarea p{margin-top:0;}
<div class='textarea' contenteditable='true' id='sec1'>blabla</div>

But the basic problem is that IE creates different HTML.
Also have a look at avoid ie contentEditable element to create paragraphs on Enter key which comes with its own issues (explained in the answer & comments there)

EDIT from op First thanks for the great answer. Second, this is how I fixed this using JS:

this.iebreak = function (event) {
    if (event.which == 13 && !event.shiftKey) {
        event.preventDefault();
        this.field.appendChild(document.createElement("br"));
    }
}

and of course add this if your' on i.e.:

this.field.addEventListener('keydown',function(event){thisObject.iebreak(event);});
Community
  • 1
  • 1
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317