Camden Reslink
Camden Reslink

Reputation: 333

Curious Keydown Behavior in Jquery

I am trying to create a textbox that is horizontally resizable, draggable, and dynamically changes its height based on what is typed inside. Here is my code so far

HTML:

<div id="text_container">
    <div id="my_text" contenteditable="true"></div>
</div>

CSS:

#text_container {
    border: #4A4A4A 2px solid;
    background: #EFEFEF;
    width: 150px;
    padding: 5px;
}

#my_text {
    width: 100%;
    border: #000 1px solid;
    background: #fff;  
    font-size: 40px;
}

jQuery:

$('#text_container').resizable( { handles: 'e' } ).draggable();

$('#my_text').keydown( function() {
    $('#text_container').css( { height: ($( this ).height() + 2) } );
});

$('#text_container').resize( function() {
    $('#text_container').css( { height: ($( '#my_text' ).height() + 2) } );
});

This makes the box change correctly with the horizontal resizing, but when I need to have it resize by skipping down a line, I have to type in one more character than I should have to. Using keypress gives the same results, and keyup doesn't resize until the key has been released, so if a person is holding down a key, it won't resize the div until the person releases the key, which doesn't seem optimal to me. Any thoughts on this?

Here is a fiddle: http://jsfiddle.net/UA3QS/65/ ​ ​

Upvotes: 0

Views: 148

Answers (1)

nathan
nathan

Reputation: 5506

The input value is not set to the new value in keydown. You can use the keyup event instead:

$('#my_text').keyup( function() {
    $('#text_container').css( { height: ($(this).height() + 2) });
});

Upvotes: 1

Related Questions