How do I persist the user selection of a text input when focus is lost and regained in IE?
PROBLEM
In Chrome/Firefox, the user's selection is returned perfectly, even when the field is out of focus. In IE, the selection is set to 0 when a field is out of focus.
CODE
I'm currently using jQuery.caret() to determine user selection, which uses the following code:
if ( this[0].setSelectionRange ) {
begin = this[0].selectionStart;
end = this[0].selectionEnd;
} else if ( document.selection && document.selection.createRange ) {
var range = document.selection.createRange();
begin = 0 - range.duplicate().moveStart( 'character', -100000 );
end = begin + range.text.length;
}
return { begin: begin, end: end };
DETAILS
I'm working on a very complicated autocomplete solution. Selecting a suggestion using the keyboard is fine, since focus is never lost from the text input. Using the mouse, however, blurs the text input and then refocuses it.
The user's selection and caret position are important to how the suggestion is filled into the field.
DISCUSSION
I'd rather not have to save the user's caret position every time they move it (keydown of left, right, up, down arrows, page up/down, backspace, mouse events click, etc) and it seems like there should be an answer that lets me either:
- Listen for some event that I can save the caret before the blur happens (onBlur is too late).
- Use a different method to determine user selection in IE.
Once again, this issue is only observed in IE. Other browsers h开发者_如何学编程andle this properly.
IE selection works a bit differently. Check out this fiddle: http://jsfiddle.net/KC48j/11/
精彩评论