iscroll icon indicating copy to clipboard operation
iscroll copied to clipboard

Scroll element into view if it's currently not visible

Open nonplus opened this issue 12 years ago • 5 comments

In my app, I'd like to ensure that the focused input element is visible after a window resize (due to Android virtual keyboard being shown).

I can't use scrollToElement() since it places the target element in the top-left corner (or center) of the viewport. I need a variant of this function that does the following:

  • If element is already visible, don't do anything
  • If element is above view port, place it at the top of the viewport
  • If element is below view port, place it at the bottom of the viewport
  • If element is to the left/right of view port, place at the left/right side of view port

nonplus avatar Jun 25 '14 18:06 nonplus

BTW, I have it implemented as a new revealElement(el, time, marginX, marginY, easing). Are you interested in a PR and would this be an appropriate name for the function?

    revealElement: function (el, time, marginX, marginY, easing) {
        el = el.nodeType ? el : this.scroller.querySelector(el);

        if ( !el ) {
            return;
        }

        var pos = utils.offset(el);

        // Top-left el corner scrolled to top-left viewport
        pos.left -= this.wrapperOffset.left;
        pos.top  -= this.wrapperOffset.top;

        // Adjust horizontally
        if((pos.left - el.offsetWidth) < (this.x - this.wrapperWidth)) {
            // reveal from right
            pos.left += this.wrapperWidth - (el.offsetWidth + (marginX||0));
        } else if(pos.left < this.x) {
            // no change
            pos.left = this.x;
        } else {
            // reveal from left
            pos.left = pos.left + (marginX||0);
        }

        // Adjust vertically
        if((pos.top - el.offsetHeight) < (this.y - this.wrapperHeight)) {
            // reveal from bottom
            pos.top += this.wrapperHeight - (el.offsetHeight + (marginY||0));
        } else if(pos.top < this.y) {
            // no change
            pos.top = this.y;
        } else {
            // reveal from top
            pos.top = pos.top + (marginY||0);
        }

        if(pos.left != this.x || pos.y != this.y) {
            time = time === undefined || time === null || time === 'auto' ? Math.max(Math.abs(this.x-pos.left), Math.abs(this.y-pos.top)) : time;

            this.scrollTo(pos.left, pos.top, time, easing);
        }
    },

nonplus avatar Jun 25 '14 18:06 nonplus

:+1: A definite nice to have.

ming-codes avatar Sep 25 '14 21:09 ming-codes

+1 😃

filipmares avatar Sep 28 '14 16:09 filipmares

Nice!

if(pos.left != this.x || pos.y != this.y)

should be

if(pos.left != this.x || pos.top != this.y)

ziriax avatar Jun 08 '15 16:06 ziriax

This is great, and would be a very useful addition!

jasongisstl avatar Dec 14 '15 17:12 jasongisstl