jquery.caret.js (1606B)
1 // Set caret position easily in jQuery 2 // Written by and Copyright of Luke Morton, 2011 3 // Licensed under MIT 4 (function ($) { 5 // Behind the scenes method deals with browser 6 // idiosyncrasies and such 7 $.caretTo = function (el, index) { 8 if (el.createTextRange) { 9 var range = el.createTextRange(); 10 range.move("character", index); 11 range.select(); 12 } else if (el.selectionStart != null) { 13 el.focus(); 14 el.setSelectionRange(index, index); 15 } 16 }; 17 18 // The following methods are queued under fx for more 19 // flexibility when combining with $.fn.delay() and 20 // jQuery effects. 21 22 // Set caret to a particular index 23 $.fn.caretTo = function (index, offset) { 24 return this.queue(function (next) { 25 if (isNaN(index)) { 26 var i = $(this).val().indexOf(index); 27 28 if (offset === true) { 29 i += index.length; 30 } else if (offset) { 31 i += offset; 32 } 33 34 $.caretTo(this, i); 35 } else { 36 $.caretTo(this, index); 37 } 38 39 next(); 40 }); 41 }; 42 43 // Set caret to beginning of an element 44 $.fn.caretToStart = function () { 45 return this.caretTo(0); 46 }; 47 48 // Set caret to the end of an element 49 $.fn.caretToEnd = function () { 50 return this.queue(function (next) { 51 $.caretTo(this, $(this).val().length); 52 next(); 53 }); 54 }; 55 }(jQuery));