droidus
droidus

Reputation: 641

textbox auto resize on click

I am trying to have a text box resize on click.

in the head:

<style>
.expand {
    height: 1em;
    width: 50%;
    padding: 3px;
}
</style>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>
$('textarea.expand').focus(function () {
    $(this).animate({ height: "1000px" }, 500);
});
</script>

and body:

<form>
<textarea class="expand" rows="1" cols="10"></textarea>
</form>

it is not expanding for me.

Upvotes: 1

Views: 1950

Answers (2)

David Thomas
David Thomas

Reputation: 253318

The reason it doesn't work is that you haven't specified event-binding on $(document).ready(), so the events are bound before the elements exist in the DOM. Try this:

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>
$(document).ready(function(){
    $('textarea.expand').focus(function () {
        $(this).animate({ height: "1000px" }, 500);
    });
});
</script>

JS Fiddle demo.

It's also worth noting that, in the more up-to-date browsers, you don't necessarily require JavaScript for this:

.expand {
    height: 1em;
    width: 50%;
    padding: 3px;
    -webkit-transition: all 1s linear;
    -0-transition: all 1s linear;
    -ms-transition: all 1s linear;
    -moz-transition: all 1s linear;
    transition: all 1s linear;
}

.expand:focus {
    height: 1000px;
    -webkit-transition: all 1s linear;
    -0-transition: all 1s linear;
    -ms-transition: all 1s linear;
    -moz-transition: all 1s linear;
    transition: all 1s linear;
}​

JS Fiddle demo.

Upvotes: 3

Whoa
Whoa

Reputation: 1334

The code looks fine, and it's running properly in JS Fiddle - http://jsfiddle.net/Pt3d8/1/. You might want to check to make sure that the Google JSAPI is properly pulling jQuery!

Upvotes: 0

Related Questions