FitFrame.js - Responsive iframes made easy

I recently completed a responsive theme for Fabrik and therefore needed to make embedded media responsive (YouTube, Vimeo etc.).

We also had to support content loaded dynamically from embed.ly and in some cases resize iframes based on the height of their container rather than width.

I've packaged our solution to this in a jQuery plugin called FitFrame.js. You can download the source and supporting demos from GitHub.

Usage

$('.container').fitFrame();

Example:

http://dev-preview.onfabrik.com/blog

Adding elements at runtime

// call update after you've added new iframes to the DOM
$('.container').fitFrame('update');

// alternatively wrap the element before it's added:
var wrapped = $('.container').fitFrame('wrap', $(iframeHtml));      
$('.add-embed').before(wrapped);

Resize Mode

FitFrame.js supports wrap (the default) and resize modes. The latter binds to the window resize event and adjusts the dimensions of the iframe to fit its container. In most cases you should just use the wrap mode. The main reason resize mode was added was to support fitting an iframe to the container height:

$('.container').fitFrame({
 mode: 'resize',
 fitHeight: true
});

Example:

http://dev-preview.onfabrik.com/portfolio/kimbra-settle-down-live

You'll find more examples on GitHub.

It's been a while since I've created any jQuery plugins so I've tried to follow best practices with this one. That said, there is some refactoring to do as there are a few code smells (feel free to send a pull-request).

One thing that I was keen to implement was a destroy function. As I've been doing more responsive web development I'm finding it increasingly frustrating when plugins don't clean up after themselves. Sometimes we need to load different plugins based on the viewport size and this can be very difficult when a plugin doesn't provide a destroy function.

So to destroy FitFrame.js:

$('.container').fitFrame('destroy');

Enjoy!


Ben Foster

About Me

I'm a software engineer and aspiring entrepreneur with 12+ years experience in the tech industry and have worked with startups and SMB’s in areas such as healthcare, recruitment and e-commerce (I even worked in enterprise, once). I founded my first startup Fabrik in 2011.

I now head up the engineering team at Checkout.com. If you're interested in working in an exciting fin-tech company, drop me a message on Twitter.

Creative Commons Licence