Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

center modal in respect to visible viewport within iFrame Facebook

I'm working on a Facebook campaign that is presented in a tab. Facebook.com loads the campaign within an iFrame. The campaign is build using Bootstrap 3.

I'd like to position a modal horizontally and vertically centered in respect to the visible viewport of the iFrame to make sure the user sees the modal. However the height of the iFrame is constantly reset by Facebook using a JS script called AutoGrow(). In that way the content within the iFrame can reload with AJAX and so removes the possibility of a double scrollbar (one for Facebook.com, one for the iFrame).

In order to get the modal which is in the iFrame centered to the user, the script:

  • needs to know if the iFrame is visible to the screen, if so
  • the height of the visible part of the iFrame

I found a code snippet that gives an idea, however this code uses the total height of the document, not the visible part of an iFrame. http://codepen.io/shshaw/pen/gEiDt

I wonder if vertically centering within an iFrame's viewport can be done.

1 Answer

Allright, found Facebook provides you with information about the parent frame, which makes it possible to center a modal within the Facebook iFrame: https://developers.facebook.com/docs/reference/javascript/FB.Canvas.getPageInfo

For anyone who is wrestling with the same issue later. Example code below positions the Bootstrap3 Modal vertically centered relative to the visible viewport of the iFrame. Change the $myDialog variable to select the right modal in your HTML.

FB.Canvas.getPageInfo(
    function(info) {
        // Get the document offset of FB iFrame: FB scrollTop - FB offsetTop = offsetTop canvas
        var offset = info.scrollTop - info.offsetTop;

        // Get the window viewport height of FB iFrame: FB clientHeight - FB offsetTop 
        var viewportHeight = info.clientHeight - info.offsetTop;

        // cache your dialog element
        var $myDialog = $('.modal-dialog');

        // now set your dialog position
        var positionWindow = (offset  + (viewportHeight/2)) - ($myDialog.outerHeight()/2);
        var styles = {
            'top' : positionWindow
        };
        $myDialog.css( styles );
    }
);