Search code examples
javascriptjqueryiframefancyboxfancybox-2

Setting height of fancybox 2.1.4 iframe dynamically after contents finish rendering


We have some jQuery graphs that load into a fancybox iframe. Recently, some of these graphs are too tall for the fancybox frame, and the design requirement is that there is no scroll bar unless the height is over 700px AND there is no more than 10px of whitespace above and below the graph.

I tried this:

afterLoad : function(){
    //(...)
    $('.fancybox-inner').height($('.fancybox-iframe').contents().height() + 20);
    console.log($('.fancybox-inner').height());
}

The console.log() correctly displays the desigred height.

But the fancybox is still displayed with the default height.

Putting a breakpoint on the console.log() line, the page displays the fancybox frame on the top of the window, graph rendered and iframe with the correct height. When I release the debugger stop, fancybox moves the frame to the center of the viewport, and it is back to the default height (the same behavior when not in debug mode).

How can I make fancybox use the desired height? It depends on the graph, so I cannot set it in the options.


Solution

  • Dealing with iframes make things a bit difficult but you may try something like

    $(document).ready(function () {
        $("a.fancybox").fancybox({
            type: "iframe",
            fitToView: false, // we need this
            autoSize: false, // and this
            maxWidth: "95%", // and this too
            beforeShow: function () {
                // find the inner height of the iframe contents
                var _newHeight = $(".fancybox-iframe").contents().find("html").innerHeight();
                this.height = _newHeight
            }
        }); // fancybox
    }); // ready
    

    Notice we disable fitToView and autoSize to be able to set the preferred height, however we also need to set a maxWidth to avoid fancybox going off screen dimensions.

    Also notice we used the beforeShow callback to set the this.height setting.

    JSFIDDLE