1

I am using a contenteditable on my page. When the user focuses the div, the height is set in js. (Needed to show buttons irreverent to the this issue) If the user types a significant amount of text, as to push multiple lines, it overflows the box and is hidden. How can I detect when additional lines are added or removed? Thanks!


HTML: <div id="edit" contenteditable="true">I can be edited.</div>

jQuery:

$("#edit").focus(function(){
    t=$(this);
    t.css('height',t.height()+10);
}).blur(function(){
    $(this).css('height','');  
});

Demo: http://jsfiddle.net/f8D4b/

Mooseman
  • 18,763
  • 14
  • 70
  • 93

2 Answers2

2

Try this method, it sets the height to "auto" to override the css setting, then sets the height after each keyup event (demo):

$("#edit").on('focus keyup', function () {
    var t = $(this);
    t.css('height', 'auto');
    t.css('height', t.height() + 10);
}).on('blur', function () {
    $(this).css('height', '');
});
Mottie
  • 84,355
  • 30
  • 126
  • 241
  • Works for me. The only issue is that if the user holds down a key, the new height doesn't fire until the actual `keyup`. Thanks! – Mooseman Jun 05 '14 at 12:38
  • You can change the binding to `keydown` instead. – Mottie Jun 05 '14 at 12:42
  • It still won't fire after each character. I don't believe there is an event for that. You'd have to use a very short interval and constantly check the length. – Mooseman Jun 05 '14 at 12:51
1

You don't need to detect when additional lines are added or removed, you just need to modify the following code.

$("#edit").focus(function(){
    t=$(this);
    t.css('min-height',t.height()+10);
}).blur(function(){
  $(this).css('min-height','');  
});

Check the update fiddle

Sandeeproop
  • 1,756
  • 1
  • 12
  • 18
  • Make sure that fiddle has the same line you have in your post: `$(this).css('min-height',''); ` – drew_w Jun 05 '14 at 12:28
  • I think what is desired is that the div collapses when it doesn't have focus. – Mottie Jun 05 '14 at 12:30
  • The only problem with this code is that the div won't maintain the 10px space at the bottom. I could use `padding`, but that won't work with the rest of my code. – Mooseman Jun 05 '14 at 12:36