March 5, 2014

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!

© 2022 Ben Foster