Try my app Expense Manager @ google play and amazon store.

Sunday, May 28, 2017

How To: Set and Get Cursor Position in Textbox using JQuery

In this tutorial, we 'll learn how to set and get cursor position in text box using jquery.
1). Open notepad, and paste following html code in it.

 <input id="first_name" type="text" value="webdesignpluscode" />
 <input onclick="SetPosition();" type="button" value="Set Position" />
 <input onclick="GetPosition();" type="button" value="Get Position" />

2). Click File then Save As... in notepad menu. Save As dialogue will open
3). Enter "home.html" in File name:
4). Select All Files in Save as type:
5). Click Save. Notepad file will be saved as html page.
6). Now open this html page in edit mode.
7). Add following online JQuery library reference inside <head> tag.

<script src="" type="text/javascript"></script>

You can download and add to project locally.

8). Now add java script block inside <head> tag and copy following code there.

<script type="text/javascript">

// Set Cursor Position
 $.fn.setCursorPosition = function (position)
 this.each(function (index, elem) {
 if (elem.setSelectionRange) {
 elem.setSelectionRange(position, position);
 else if (elem.createTextRange) {
 var range = elem.createTextRange();
 range.moveEnd('character', position);
 range.moveStart('character', position);;
 return this;

 // Get cursor position
 $.fn.getCursorPosition = function ()
 var el = $(this).get(0);
 var position = 0;
 if ('selectionStart' in el) {
 position = el.selectionStart;
 else if ('selection' in document) {
 var Sel = document.selection.createRange();
 var SelLength = document.selection.createRange().text.length;
 Sel.moveStart('character', -el.value.length);
 position = Sel.text.length - SelLength; }
 return position;

 function SetPosition() {

 function GetPosition() {

Complete code can be downloaded from this git repository.

This is all. You have done. Save file, and view it in any browser.

No comments:

Post a Comment

Follow by Email

Google+ Badge