views:

38

answers:

4

I have a <textarea> element in my form that has this code attached to it:

$('#links').focusin(function() {
    $('#links').animate({
        height: '100px'
    }, 300, function() {
        // done
    });
});

This works perfectly, when the text area gets focus it increases in height nicely to 100px. Now, I want it to shrink back down to a suitable size based on the text inside it when it loses focus. I wrote this:

$('#links').focusout(function() {
    $('#links').animate({
        height: 'auto'
    }, 300, function() {
        // done
    });
});

But it doesn't work, it just stays at the same height (100px). Is there any way to do this?

Thanks. :)

Edit: To save some confusion, the even handler for $('#links').focusout works fine, that's the first thing I tested. So I assume it's a problem with the animation or the CSS property.

A: 

Try $( '#links' ).blur( function(){ ... } ) instead

http://api.jquery.com/blur/


Edit, your actual code:

$('#links').blur(function() {
$('#links').animate({
    height: 'auto'
}, 300, function() {
    // done
});
});

Some other notes.. You can use $( '#links' ).focus() instead of focusin, and also, once you're in the function, you can use $( this ).animate(), as a shortcut. Just little tips and whatnot.

hookedonwinter
Sorry, I should have explained better. There isn't anything wrong with the even handler, that works fine as I can test it by adding an alert. The problem seems to be with the animation or the CSS property. Unless there's any benifit to using `blur` over `focusout`?
Prupper
oh gotchya. try a different set height, just for testing.. set it to 300px or something just to make sure it's actually working?
hookedonwinter
Good idea, it works with a static value like `20px`, it must be the `auto` attribute I'm setting.
Prupper
Try inherit, or set it to an actual value.
hookedonwinter
inherit doesn't work either. Ah well, i'll just set it to a realistic static height. Thanks :)
Prupper
You could even grab the height before you change it, and then change it back to the original. original_height = $( '#links' ).height()
hookedonwinter
A: 
auto_height_link = $( '#links' ).css('height');
$('#links').focusin(function() {
    $(this).animate({
        height: '100px'
    }, 300, function() {
        // done
    });
}).focusout(function() {
    $(this).animate({
        height: auto_height_link
    }, 300, function() {
        // done
    });
});

but anyways the animate doesnt read the css value auto for height

i stumbled upon this http://www.unwrongest.com/projects/elastic/ which is what you need i guess

A: 

This isn't quite the same as what you're doing, but quite similar: http://james.padolsey.com/javascript/jquery-plugin-autoresize/

Darryl Hein
A: 

You can't use auto to animate in jQuery. You should set it to auto, then get the actual height (in px) and finaly animate it.

Take a look here

Kaaviar