Skip to content

Commit

Permalink
Mask: Initial draft of _caret, implementation borrowed from @digitalBush
Browse files Browse the repository at this point in the history
 maskedInput plugin
  • Loading branch information
gnarf committed Jul 27, 2011
1 parent 5b7fa97 commit 9dacfd1
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 3 deletions.
2 changes: 1 addition & 1 deletion tests/unit/mask/mask.html
Expand Up @@ -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>
26 changes: 26 additions & 0 deletions tests/unit/mask/mask_core.js
Expand Up @@ -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 ) );
41 changes: 39 additions & 2 deletions ui/jquery.ui.mask.js
Expand Up @@ -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.