Microsoft Dot Net Master

Microsoft Dot Net Master
Microsoft Dot Net Master

Friday, May 3, 2013

jQuery and Fancybox: How to automatically set the height of an iframe lightbox


Fancybox is a pretty cool lightbox plugin for jQuery that I have been using for awhile now. It’s got a great feature set, looks good, and for the most part it just works out of the box. There is however one thing that was mind numbingly hard to figure out, and that was how to automatically set the height of an iframe lightbox. Fancybox has this functionality built in for inline content via the autoDimensions key, which is set to true by default. Unfortunately this is not the case for iframes. After some hair pulling I managed to piece together an auto height solution for Fancybox iframes, but this technique could also be used without Fancybox to find the height of any iframe.

Like most web challenges, the fix is quite simple, but almost every example I found always seemed to be missing one important piece of the puzzle.

$("#lightbox").fancybox({
      'hideOnContentClick' : true,
      'width' : 500,
      'type' : 'iframe',
      'padding' : 35,
      'onComplete' : function() {
        $('#fancybox-frame').load(function() { // wait for frame to load and then gets it's height
          $('#fancybox-content').height($(this).contents().find('body').height()+30);
        });
      }
    });


In the above example we have given our lightbox an id of #lightbox. We initialize the plugin with some options and give it a type option of iframe. Now you can create your separate HTML file for the lightbox and link to it form your main page and give the link href an id of #fancy-box. If you would like to use multiple lightboxes on one page you could use a class instead of an id.

The iframe height magic happens when the onComplete event is triggered. Here you can set up a call call jQuery’s load function which will then be used to call the height function after the iframe has loaded—you cannot get the height until the frame source has fully loaded. The id of #fancybox-content is the name of the div that Fancybox wraps the iframe in. We then set the height of that div by checking the contents of the iframe and using jQuery’s find method to locate the body tag and then get the height. I found that the height was always off by about 30 pixels, thus the +30. This may be due to paddings and margins within the loaded HTML file, but you can fiddle around with it until you get the right offset. You should now have an iframed lightbox that auto sizes its height.