Friday, June 22, 2012

Positioning popup in a long iframe

Image: http://www.happynews.com


You must have got from the previous posts that we were involved in the development of Shopping Community that shows up on the retailers' website or within Facebook in an iframe. Shopping Community is actually an activity feed of users' action on products. By default, a feed tile has limited information and when user wants to see details, we open a light-box popup.

The Challenge
The popup showing details must be positioned in a way so that it appears in center of the window (read viewport). When the page was opened in the browser window, the solution was very simple.

popup_top = window.scrollTop + (screen.height - popup_height)/2

But as soon as it came into the tall iframe, window.scrollTop always remains 0 because the window in iframe never has a scrollbar. It is the parent window that has a scrollbar but the Javascript code inside iframe does not have access to that; again because of cross-domain communication issue.
When user has scrolled down in the page, popup opens in somewhere near the top :(. We can scroll the page back to the popup position by putting an anchor but that creates a bad user expirience for 2 reasons:
1. An unexpected jerk that is introduced by moving the page up.
2. User has lost the place where she was after closing the popup.

The Solution
So it was very important to figure out some way of positioning the popup such the popup shows up in the middle (well as best as possible)  in front of user's eyes without changing the scroll position of the page.

The only way out was to figure out the current scroll position. One was of course using cross-domain communication but doing without that was much better and reliable. BTW, as this was to be done within the iframe, we could use jquery, backbone and coffscript.




As you can see the code above, we captured the pageY and screenY properties of the click event object. This actually tells co-ordinates of the point where user clicked. As name of the properties suggest, the co-ordinates are with respect to page and with respect to screen. By subtracting them, we estimated the amount of scroll. This is not accurate but works for practical situations.

Now, it was simple to use the same formula to find out the popup top.

Hope this helps.
If I am not clear in my post, please shoot questions.