Positioning a dialog on a Facebook Canvas Page

Positioning a dialog on a Facebook Canvas Page

As promised (or threatened) here is a post on some little Facebook development insight gained through some trial, error, blood, sweat, and yes tears.

A problem I was having was accurately determining the x, y position of a given control for popping up informational dialogs. Sure, it was easy enough to use the getAbsoluteTop and getAbsoluteLeft calls to get the absolute positioning (supposed), but after playing around with these calls it became apparent that “absolute” didn’t mean “absolute” in the sense that most web / windows developers would understand. It really is a relative offset – but to what?

After perusing the FBJS docs, and finding no mention of a viewport (which is really what I was trying to determine the offset from), I took a total flier and thought – “well, if I could jet get the root element of my document, and find ITS x and y, I should be home free.

Bingo. That was the trick. Use document.getRootElement() to get the container element.

The code below demonstrates the technique.

var argCtl = document.getElementById(“myForm”);
var newTop = argCtl.getAbsoluteTop();
var newLeft = argCtl.getAbsoluteLeft();
var scrollW = argCtl.getScrollWidth();
var root = document.getRootElement();
var cTop = root.getAbsoluteTop();
var cLeft = root.getAbsoluteLeft();

document.getElementById(“confirm_dialog1”).setStyle(“top”, (newTop – cTop) + “px”);
document.getElementById(“confirm_dialog1”).setStyle(“left”, (newLeft – cLeft) + “px”);

First, grab a reference to an object on the page that you wish to position relative to (in this case, I am using a form named “myForm”). Get its x and y coordinates.

Next, get the container x and y by getting its reference (document.getRootElement()) and then its x and y values (getAbsoluteTop and getAbsoluteLeft).

Finally, to accurately position a dialog where an element exists, take the difference between the container and the element being positioned:

document.getElementById(“confirm_dialog1”).setStyle(“top”, (newTop – cTop) + “px”);
document.getElementById(“confirm_dialog1”).setStyle(“left”, (newLeft – cLeft) + “px”);

Voila. You’ve just positioned a dialog over an element.

In practice, you would want some arbitrary additional offset from the control so that you don’t hide it when you pop up / display your dialog. I’ll leave that as an exercise for the reader.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s