Question

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 :)

Was it helpful?

Solution 2

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

OTHER TIPS

your code is great - i just added some milliseconds of timeout (around 100-200 is enough) and now it behaves nicely. Just wondered what that on('focus') event handler is for. And guess you can skip calling focus() in resize() function...

I use the following for ALL mouse position issues and have never had a problem. I don't see why it wouldn't work for this instance aswell.

var cX;
var cY;
document.onmousemove = function(e){
    cX = e.pageX;
    cY = e.pageY;
}

You could use it like I have:

window.scrollTo(0, cX);

Or simply put the e.pageX into your code example. cX, cY are cursor coordinates.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top