Skip to content

Instantly share code, notes, and snippets.

@rowanmanning
Created June 28, 2010 11:40
Show Gist options
  • Save rowanmanning/455732 to your computer and use it in GitHub Desktop.
Save rowanmanning/455732 to your computer and use it in GitHub Desktop.
Cross-browser caret position
/*
* jQuery caret Plugin 0.2
*
* Tested in jQuery 1.4.2
*
* Copyright 2010, Rowan Manning (http://www.rowanmanning.co.uk/)
* Dual licensed under the MIT or GPL Version 2 licenses
*/
(function($){
//============================================================
// caret position functions
// get the caret position of an element
$.getCaretPosition = function(elem){
// get the element
var $elem = $(elem);
// default caret position
var caretPosition = 0;
// ie way of doing things
if (document.selection){
// set focus on the element
$elem.focus();
// get empty selection range
var selection = document.selection.createRange();
// move selection start to 0 position
selection.moveStart('character', -$elem.val().length);
// the caret position is selection length
caretPosition = selection.text.length;
}
// proper way of doing things
else if (elem.selectionStart || elem.selectionStart=='0'){
// the caret position is a lot easier to determine
caretPosition = elem.selectionStart;
}
// return the caret position
return caretPosition;
}
// set the caret position of an element
$.setCaretPosition = function(elem, caretPosition){
// TODO write this
}
//============================================================
// caret position methods
// get/set the caret position of an element
$.fn.caret = function(caretPosition){
// is caretPosition is a number?
if ((caretPosition-0)==caretPosition && caretPosition.length>0){
// set the caret position
$.setCaretPosition(this[0], caretPosition);
// return original object for chaining
return this;
}
else{
// get the caret position
return $.getCaretPosition(this[0]);
}
}
//============================================================
}(jQuery));
/*
* jQuery getCaretPosition Plugin 0.2
*
* Tested in jQuery 1.4.2
*
* Copyright 2010, Rowan Manning (http://www.rowanmanning.co.uk/)
* Dual licensed under the MIT or GPL Version 2 licenses
*/
(function(b){b.getCaretPosition=function(a){var d=b(a),c=0;if(document.selection){d.focus();a=document.selection.createRange();a.moveStart("character",-d.val().length);c=a.text.length}else if(a.selectionStart||a.selectionStart=="0")c=a.selectionStart;return c};b.setCaretPosition=function(){};b.fn.caret=function(a){if(a-0==a&&a.length>0){b.setCaretPosition(this[0],a);return this}else return b.getCaretPosition(this[0])}})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment