Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get the window scroll position in Facebook API?

In the FB.Canvas API there are methods to get the scroll top, offset top and client height (through getPageInfo()) but I need a way to find the top most window scroll position so I can determine if the area I need to be visible to the client are in view. The users will be tabbing through a form and it is taller than most screens. I need to ensure the form item is visible.

like image 943
1.21 gigawatts Avatar asked Oct 10 '22 08:10

1.21 gigawatts


1 Answers

It appears that the getPageInfo().scrollTop property and the getPageInfo().offsetTop together will give you the top window scroll position.

Here is the final code I used to scroll elements into view given the absolute / global x and y coordinates.

function scrollElementIntoViewFB(applicationID, elementTop, elementBottom) {
    var pageInfo = FB.Canvas.getPageInfo();

    // fallback if running local
    if (pageInfo.clientHeight==0) {
         scrollElementIntoView(applicationID, elementTop, elementBottom);
         return;
    }

    var scrollPosition = pageInfo.scrollTop;
    var viewportHeight = pageInfo.clientHeight;
    var flashOffsetTop = pageInfo.offsetTop;
    var elementAbsoluteTop = elementTop + flashOffsetTop;
    var elementAbsoluteBottom = elementBottom + flashOffsetTop;
    var visibleBottomPosition = viewportHeight + scrollPosition;

    if (scrollPosition>elementAbsoluteTop) {
        FB.Canvas.scrollTo(0, elementAbsoluteTop);
    }
    else if (visibleBottomPosition<elementAbsoluteBottom) {
        FB.Canvas.scrollTo(0, elementAbsoluteBottom-viewportHeight);
    }


    return true;
}

And if for some reason you want the HTML only version (which will not work if in a iframe inside another domain like Facebook but will work on your own site):

function scrollElementIntoView(applicationID, elementTop, elementBottom) {
    var scrollPosition = f_scrollTop();
    var viewportHeight = f_clientHeight();
    var flashElement = swfobject.getObjectById(applicationID);
    var flashOffsetTop = flashElement.offsetTop; // not sure if this is cross browser   
    var elementAbsoluteTop = elementTop + flashOffsetTop;
    var elementAbsoluteBottom = elementBottom + flashOffsetTop;
    var visibleBottomPosition = viewportHeight + scrollPosition;

    if (scrollPosition>elementAbsoluteTop) {
        window.scrollTo(0, elementAbsoluteTop);
    }
    else if (visibleBottomPosition<elementAbsoluteBottom) {
        window.scrollTo(0, elementAbsoluteBottom-viewportHeight);
    }

    return true;
}

Search online for the other functions by their names and you'll find the rest of the code.

like image 139
1.21 gigawatts Avatar answered Oct 18 '22 12:10

1.21 gigawatts