Textarea element get focus cursor position last character

Source: Internet
Author: User

In the html element, textarea is a chicken rib. The obtained focus cursor cannot locate the last character. The author has a simple rich text box in the project, requiring users to enter characters and support emoticons at the same time. After an emoticon is selected, textarea obtains the focus, and the cursor stays at the top of textarea In the chrome browser. The conclusion is that different browsers have different focus implementations on the textare element.

The solution is as follows:

<Script type = "text/javascript"> function moveCaretToEnd (el) {if (typeof el. selectionStart = "number") {el. selectionStart = el. selectionEnd = el. value. length;} else if (typeof el. createTextRange! = "Undefined") {el. focus (); var range = el. createTextRange (); range. collapse (false); range. select () ;}} var textarea = document. getElementById ("test"); textarea. onfocus = function () {moveCaretToEnd (textarea); // Work around Chrome's little problem window. setTimeout (function () {moveCaretToEnd (textarea) ;}, 1) ;}; </script> <textarea id = "test"> Something </textarea>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.