Home >Web Front-end >JS Tutorial >How to Build an Auto-Expanding Textarea jQuery Plugin, Part 1
Automatically expanding text areas is very popular on sites like Facebook. The height of the text area box expands and shrinks according to the amount of text entered by the user. This has several advantages:
View the extended text area demonstration...
This three-part tutorial describes how to build an automatically extended text area using HTML and reusable jQuery plug-in. By the end of the third part, you will understand how it works and have code that can be used in your own project.
Like all good developers, we should fully understand the system requirements:
We implement the solution as a jQuery plugin. jQuery is mainly used to handle more mundane aspects such as DOM sniffing and event delegating; you can easily rewrite your code using another framework.
However, how do we know when we should resize the text area and what height to use?
First, we can assign a "keyup" event handler to any text area. This will call a function immediately after the key is pressed and the text is modified.
We can then check the DOM scrollHeight property. This will return the height of the internal scrolling part, i.e. the height of the text entered by the user. If we set the height of the text area to the current scrollHeight value, the scrollbar will become irrelevant. Unfortunately scrollHeight is not W3C recommendation, and we need to overcome some cross-browser inconsistencies:
We also need to consider the scrollbar. By default, most browsers only display text area scroll bars when needed. However, if we set overflow to "auto", the scroll bar will appear when we add a new line and then disappear when we change the height of the text area. Setting overflow to "hidden" will resolve the flashing scrollbar issue, but this must never be applied to non-extended text areas or text areas that have been extended beyond their specified maximum height.
Lastly, browser window resizing can be a problem. Fluid web design can implement text areas with a percentage-based width: resizing windows will resize the box. While we can detect window resize, the event performs poorly in IE and calls handlers quickly. We can solve this problem, but resizing multiple text areas can cause page design to jump and confuse users. So after resizing, we will only adjust the height of the text area after the user switches focus to the box.
There is a lot of content to absorb, and there is more! Make yourself a cup of coffee and get ready for the second part...
The above is the detailed content of How to Build an Auto-Expanding Textarea jQuery Plugin, Part 1. For more information, please follow other related articles on the PHP Chinese website!