I have an expanding textarea. When the textarea has already expanded enough to reach the bottom of the window, the body flickers/scrolls back to the top of the textarea and you cannot see the last characters you've keyed in unless you scroll the window.
The sample can be found in this jsfiddle. I tried adding a scrollTo to the body
window.scrollTo(0, document.getElementsByTagName('textarea')[0].getBoundingClientRect().bottom);
How can I calculate the offset of the cursor in textarea from the window? I was thinking of getting the top offset of the cursor and just scrolling the window to its position if the cursor is already beyond the fold.
Help on this would be greatly appreciated :)
I found a solution right here in stack! https://stackoverflow.com/a/18262927/769326
I added the code snippet found there in the resize function also.
function resize(e){
var text = _this.value,
lines = text.split('\n'),
cursorPosition = $this.getCursorPosition(),
scrollLeft = window.pageXOffset || (document.documentElement || document.body.parentNode || document.body).scrollLeft,
scrollTop = window.pageYOffset || (document.documentElement || document.body.parentNode || document.body).scrollTop;
for(var i = 0, length = lines.length; i < length; i++){
if(lines[i].length <= settings.charactersPerLine){
continue;
}
var j = 0,
space = settings.charactersPerLine;
while(j++ <= settings.charactersPerLine){
if(lines[i].charAt(j) === ' '){
space = j;
}
}
lines[i+1] = lines[i].substr(space) + (lines[i + 1] || '');
lines[i] = lines[i].substr(0, space);
}
_this.value = lines.join('\n');
if(cursorPosition == text.length){
setCaretToPos(_this, cursorPosition + 1);
}
else{
setCaretToPos(_this, cursorPosition);
}
_this.style.height = elementHeight;
_this.style.height = _this.scrollHeight + 'px';
_this.style.overflow = 'hidden';
window.scrollTo(scrollLeft, scrollTop);
}
here's the jsfiddle