babiro
babiro

Reputation: 85

Limit contenteditable div height

div is limited to a maximum height of 300px , when I input some text, after div reaches 300px text overflows.how to stop text input when div reaches 300px.

I used overflow:hidden; which just stops overflow, but text can still be inputted.

.editable {
overflow:hidden;
max-height:300px;
border: 1px solid #eee;
padding: 5px;
border: 1px solid #000;
outline: none;
width: 300px;
min-height: 40px;
} 

http://jsfiddle.net/zFzQe/77/

Is there a way to measure text height and limit text input to 300px ?

Upvotes: 3

Views: 4703

Answers (3)

edwardsmarkf
edwardsmarkf

Reputation: 1417

I struggled with a very similar issue. Here is what I came up after looking at several examples:

<div contenteditable='true' id="message_area" max-width: 100px;' >
</div>
<script type='text/javascript'>
jQuery("div#message_area").on('keypress', () => {
   if ( event.target.innerText.trim().length >= 10 ) {
      event.preventDefault();
      return false;
   }
});
</script>

Upvotes: 0

Chamika Sandamal
Chamika Sandamal

Reputation: 24302

Try this code, Demo

$("editable").addEvent('keypress', function (e) {
    var element = this;
    if ((element.offsetHeight < element.scrollHeight) || (element.offsetWidth < element.scrollWidth)) {
        e.stop();
    }
});

Upvotes: 2

alessandrio
alessandrio

Reputation: 4370

editable.onkeyup=function(){
  if(editable.innerHeight>='300px'){
    editable.style.height='300px';
  }
}

Upvotes: 1

Related Questions