Permalink
Browse files

Mask: Initial draft of _caret, implementation borrowed from @digitalBush

 maskedInput plugin
  • Loading branch information...
1 parent 5b7fa97 commit 9dacfd1c7268c94c014173337ed51889cf25f43a @gnarf gnarf committed Jul 27, 2011
Showing with 66 additions and 3 deletions.
  1. +1 −1 tests/unit/mask/mask.html
  2. +26 −0 tests/unit/mask/mask_core.js
  3. +39 −2 ui/jquery.ui.mask.js
@@ -32,7 +32,7 @@ <h2 id="qunit-banner"></h2>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"></ol>
<div id="qunit-fixture">
-
+<input id="mask1" type="text">
</div>
</body>
</html>
@@ -2,4 +2,30 @@
module( "mask: core" );
+test( "_caret() can move and read the text cursor", function() {
+ expect( 3 );
+
+ var input = $( "#mask1" ).val("This string is 33 characters long").mask(),
+ instance = input.data( "mask" );
+ input.focus();
+
+ instance._caret( 0 );
+ deepEqual( instance._caret(), {
+ begin: 0,
+ end: 0
+ }, "Caret position set to 0 results in 0, 0" );
+
+ instance._caret( 34 );
+ deepEqual( instance._caret(), {
+ begin: 33,
+ end: 33
+ }, "Caret position set beyond bounds (34) results in 33, 33" );
+
+ instance._caret( 0, 2 );
+ deepEqual( instance._caret(), {
+ begin: 0,
+ end: 2
+ }, "Caret position set to 0, 2 results in 0, 2" );
+});
+
}( jQuery ) );
View
@@ -18,8 +18,45 @@ $.widget( "ui.mask", {
},
_create: function() {
+ },
+
+ // helper function to get or set position of text cursor (caret)
+ _caret: function( begin, end ) {
+ var range,
+ elem = this.element,
+ dom = elem[0];
+
+ // if begin is defined, we are setting a range
+ if ( begin !== undefined ) {
+ end = ( end === undefined ) ? begin : end;
+ if ( dom.setSelectionRange ) {
+ dom.setSelectionRange( begin, end );
+ } else if ( dom.createTextRange ) {
+ range = dom.createTextRange();
+ range.collapse( true );
+ range.moveEnd( "character", end );
+ range.moveStart( "character", begin );
+ range.select();
+ }
+ } else {
+
+ // begin is undefined, we are reading the range
+ if ( dom.setSelectionRange ) {
+ begin = dom.selectionStart;
+ end = dom.selectionEnd;
+ } else if ( document.selection && document.selection.createRange ) {
+ range = document.selection.createRange();
+
+ // the moveStart returns the number of characters it moved as a negative number
+ begin = 0 - range.duplicate().moveStart( "character", -100000 );
+ end = begin + range.text.length;
+ }
+ return {
+ begin: begin,
+ end: end
+ };
+ }
}
});
-
-})( jQuery );
+}( jQuery ) );

0 comments on commit 9dacfd1

Please sign in to comment.