Jquery text insert cursor plug-in, compatible with FF, IE6 +, Chrom

Source: Internet
Author: User

This is a jquery plug-in. It is mainly used to insert a piece of text information to the cursor. This function sounds very simple, but it is not so easy to make it, mainly because of compatibility issues, later I checked a lot of information and found this short and sophisticated jquery plug-in. Let's share it with you.

(Function ($ ){
$. Fn. extend ({
InsertAtCaret: function (myValue ){
Var $ t = $ (this) [0];
If (document. selection ){
This. focus ();
Sel = document. selection. createRange ();
Sel. text = myValue;
This. focus ();
} Else if ($ t. selectionStart | $ t. selectionStart = '0 '){
Var startPos = $ t. selectionStart;
Var endPos = $ t. selectionEnd;
Var scrollTop = $ t. scrollTop;
$ T. value = $ t. value. substring (0, startPos) + myValue + $ t. value. substring (endPos, $ t. value. length );
This. focus ();
$ T. selectionStart = startPos + myValue. length;
$ T. selectionEnd = startPos + myValue. length;
$ T. scrollTop = scrollTop;
} Else {
This. value + = myValue;
This. focus ();
}
}
});
}) (JQuery );


Usage: $ ("select"). insertAtCaret ("text ");

If you are not used to this method, you can change it to a normal function, for example:

Function insertAtCaret (obj, myValue ){
Var $ t = obj [0];
If (document. selection ){
This. focus ();
Sel = document. selection. createRange ();
Sel. text = myValue;
This. focus ();
} Else if ($ t. selectionStart | $ t. selectionStart = '0 '){
Var startPos = $ t. selectionStart;
Var endPos = $ t. selectionEnd;
Var scrollTop = $ t. scrollTop;
$ T. value = $ t. value. substring (0, startPos) + myValue + $ t. value. substring (endPos, $ t. value. length );
This. focus ();
$ T. selectionStart = startPos + myValue. length;
$ T. selectionEnd = startPos + myValue. length;
$ T. scrollTop = scrollTop;
} Else {
This. value + = myValue;
This. focus ();
}
}

Usage is similar to the above: insertAtCaret imports a jquery object and the text to be inserted, insertAtCaret ($ ("select"), "text ");

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.