How will our auto-expanding
textarea boxes be initialized? Since our solution will be a jQuery plugin, we can implement auto-expanding functionality for every
textarea on our page using the following jQuery call:
This statement is a little crude since every textarea will auto-expand and we have not specified individual height limits. Therefore, we would probably need multiple statements for every page, e.g.
$("#textarea1").TextAreaExpander(); $("#textarea2").TextAreaExpander(50, 200); // box will size between 50 and 200 pixels $("#textarea3").TextAreaExpander(90, 300); // box will size between 90 and 300 pixels
Although this is feasible, we could have dozens of textareas. Our server-side code might also generate different
So let’s make things a little easier for ourselves and other developers using our component. If we want a
textarea to auto-expand, we will assign a class attribute of “expand” to the tag. Although the class attribute is normally used for CSS styles, it can hold other values and is available in all flavors of HTML and XHTML. Don’t worry if your textarea already has a CSS class applied — any number of space-separated values can be added:
<!-- expanding textarea --> <textarea name="textarea1" rows="3" cols="60" class="mystyle expand"></textarea>
To limit the
textarea height between a certain range, we can add the minimum and maximum values to the “expand” name, e.g.
<!-- expanding textarea, but limited between 50 and 200px --> <textarea name="textarea2" rows="3" cols="60" class="expand50-200"></textarea>
textareatags will not auto-expand by default.
- Our trigger is specified in the
- We can still use the jQuery TextAreaExpander() method when we need to, e.g. if a textarea is added to the DOM after the page has loaded.
- Progressive enhancement gives us a warm and cozy feeling!
This loads the latest jQuery library (downloaded from jQuery.com) and our new TextAreaExpander plugin code.