Ranger is cross-browser jQuery plugin, which provides methods for easy working with cursor (caret) and selections.
Just download and include it in your page:
<script src="./jquery.ranger.min.js" type="text/javascript" charset="utf-8"></script>After that all your jQuery-wrapped inputs and textareas will have new methods. Really simple, isn’t it?
Ranger extends inputs and textareas with these methods:
- getCursorPosition(inversed) — returns position of cursor. Inversed argument is optional, if is true — method returns position from the end of the text.
- setCursorPosition(position) — sets position of cursor. If position argument is negative, cursor position will be calculated from the end of the text. Returns jQuery object.
- insertAtCursor(text) — inserts text at cursor position. Returns jQuery object.
- wrapCursor(leftPart, rightPart) — wraps cursor with two parts of text. Returns jQuery object.
- select(from, to) — selects text in input. No arguments — selects all, two arguments — selects range. Supports negative arguments, for example: input.select(−1, −20) — will select text from the last symbol back to the 20th symbol from the end. Returns jQuery object.
- deselect() — deselects text. After deselecting cursor stays at selection start position.
- getSelectedText() — returns selected text.
- replaceSelectedText(text) — replaces selected text with text argument. Returns jQuery object.
- wrapSelectedText(leftPart, rightPart) — wraps selected text with two parts of text. Returns jQuery object.
As you can see, many methods return jQuery instance, so you can use chainable calls!
Ok, script is included. Let’s try Ranger:
var input = $("#test-input"); // Some <input type="text" id="test-input" />
input
.val("Test")
.setCursorPosition(2) // Te|st
.setCursorPosition(-1) // Test|
.setCursorPosition(-4) // T|est
.insertAtCursor("he t") // The t|est
.select(1, 3) // T[he] test
.select(-1, -5) // The [test]
.getSelectedText(); // "test"
// Etc.See jquery.ranger.test.js file for more examples.
Ranger was tested in the latest Chrome, the latest Opera and IE 7+.
- contentEditable support;
- Make working version for IE 6;
- Test in different versions of major browsers (FF 3.6+, Opera 9.5+, Safari 3+, Chrome);
- Make Russian version of the README.