iframe Auto Adjust Height as content changes

setInterval

The only (corrected due to advances in browser tech, see David Bradshaw’s answer) backwards compatible way to achieve this with an iframe is to use setInterval and keep an eye on the iframe’s content yourself. When it changes its height, you update the size of the iframe. There is no such event you can listen out for that will make it easy unfortunately.

A basic example, this will only work if the iframe content that has changed in size is part of the main page flow. If the elements are floated or positioned then you will have to target them specifically to look for height changes.

jQuery(function($){
  var lastHeight = 0, curHeight = 0, $frame = $('iframe:eq(0)');
  setInterval(function(){
    curHeight = $frame.contents().find('body').height();
    if ( curHeight != lastHeight ) {
      $frame.css('height', (lastHeight = curHeight) + 'px' );
    }
  },500);
});

Obviously depending on what you want you can modify the perspective of this code so that it works from the iframe, on itself, rather than expecting to be part of the main page.

cross-domain issue

The problem you will find is that due to browser security it wont let you access the content of the iframe if it is on a different host to the main page, so there isn’t actually anything you can do unless you have a way of adding any script to the html that appears in the iframe.

ajax

Some others are suggesting trying to use the third-party service via AJAX, unless the service supports this method it will be very unlikely you’ll be able to get it to work — especially if it is a booking service that will most likely need to operate over https/ssl.

As it appears you have full control over the iframe content, you have full options open to you, AJAX with JSONP would be an option. However, one word of warning. If your booking system is multistepped you need to make sure you have a well designed UI — and possibly some history/fragment management code — if you are to go down the AJAX route. All because you can never tell when a user will decide to navigate forward or back in their browser (which an iframe would automatically handle, within reason). A well designed UI can detract users from doing this.

cross-domain communication

If you have control of both sides (which it sounds like you do) you also have the cross domain communication option using window.postMessage – see here for more information https://developer.mozilla.org/en-US/docs/DOM/window.postMessage

Leave a Comment