Shadowbox: Manual popup positioning

This article has originally been published on my employer's blog: Shadowbox: Manual popup positioning @ netresearch .

Shadowbox can be used to display images, videos or other HTML pages in a popup on your website. Sometimes it is necessary to manually adjust the position of the overlay window, for example when using it in an iframe with a very large height setting. Shadowbox itself does not offer a hook to modify the position, but with some JavaScript trickery it is possible to manipulate the position nevertheless.

The idea is - since we have no hook to register with - to replace the original positioning method with our own. Since JavaScript allows method renaming, this is fairly easy.

Static position

Shadowbox uses method setDimensions() to calculate and set position and size of the popup window. We rename it and put our own method at this place:

<script type="text/javascript">
window.Shadowbox.setDimensionsOld = window.Shadowbox.setDimensions;
window.Shadowbox.setDimensions = function (height, width, maxHeight, maxWidth, topBottom, leftRight, padding, preserveAspect) {
    var S = window.Shadowbox;
    window.Shadowbox.setDimensionsOld(height, width, maxHeight, maxWidth, topBottom, leftRight, padding, preserveAspect);
    window.Shadowbox.dimensions.top = 10;
    return window.Shadowbox.dimensions;
}
</script>

Now we have our shadowbox popup fixed at 10 pixels from the top of the page.

Have a look at the static positioning demo.

Dynamic position

When you have an iframe with some several thousand pixels in height, you don't want to have a fixed position on top but a position near the mouse cursor or the element that has been clicked.

The following code positions the popup 10 pixels below the object that has been clicked to open the overlay:

<script type="text/javascript">
window.Shadowbox.setDimensionsOld = window.Shadowbox.setDimensions;
window.Shadowbox.setDimensions = function (height, width, maxHeight, maxWidth, topBottom, leftRight, padding, preserveAspect) {
    var S = window.Shadowbox;
    window.Shadowbox.setDimensionsOld(height, width, maxHeight, maxWidth, topBottom, leftRight, padding, preserveAspect);
    if (window.shadowboxClickObj && window.shadowboxClickObj.link) {
        var offset = $(window.shadowboxClickObj.link).offset();
        window.Shadowbox.dimensions.top = offset.top + 10;
        $('#sb-container').css({position: 'absolute', 'height': $(document).height()});
    }
    return window.Shadowbox.dimensions
}
 
window.Shadowbox.skin.onOpenOld = window.Shadowbox.skin.onOpen;
window.Shadowbox.skin.onOpen = function(obj, callback) {
    window.shadowboxClickObj = obj;
    window.Shadowbox.skin.onOpenOld(obj, callback);
}
</script>

Here, onOpen() needs to be overwritten as well because the clicked object is not available anymore in setDimensions().

Have a look at the dynamic positioning demo.

Written by Christian Weiske.

Comments? Please send an e-mail.