- var scroll;
- // Do nothing if hidden
- if ( !$( this ).is( ':hidden' ) ) {
- if ( this.selectionStart || this.selectionStart === 0 ) {
- scroll = getCaretScrollPosition( this );
- if ( options.force || scroll < $( this ).scrollTop() ||
- scroll > $( this ).scrollTop() + $( this ).height() ) {
- $( this ).scrollTop( scroll );
- }
+ var
+ clientHeight = this.clientHeight,
+ origValue = this.value,
+ origSelectionStart = this.selectionStart,
+ origSelectionEnd = this.selectionEnd,
+ origScrollTop = this.scrollTop,
+ calcScrollTop;
+
+ // Delete all text after the selection and scroll the textarea to the end.
+ // This ensures the selection is visible (aligned to the bottom of the textarea).
+ // Then restore the text we deleted without changing scroll position.
+ this.value = this.value.slice( 0, this.selectionEnd );
+ this.scrollTop = this.scrollHeight;
+ // Chrome likes to adjust scroll position when changing value, so save and re-set later.
+ // Note that this is not equal to scrollHeight, it's scrollHeight minus clientHeight.
+ calcScrollTop = this.scrollTop;
+ this.value = origValue;
+ this.selectionStart = origSelectionStart;
+ this.selectionEnd = origSelectionEnd;
+
+ if ( !options.force ) {
+ // Check if all the scrolling was unnecessary and if so, restore previous position.
+ // If the current position is no more than a screenful above the original,
+ // the selection was previously visible on the screen.
+ if ( calcScrollTop < origScrollTop && origScrollTop - calcScrollTop < clientHeight ) {
+ calcScrollTop = origScrollTop;