June 26, 2013 — Code
Handling media is quite often one of the most challenging parts of responsive web design. Images tend to be pretty simple to manage with a little CSS, but iframes are a lot trickier to work with. Sure, you can set a max-width of 100%, but it’s not going to keep the same aspect ratio as it resizes like images do. Thankfully, we can work a little mathematical magic with jQuery. Here’s a snippet that I’m using on a current project that embeds a lot of videos with iframes:
First, we cache all of our iframes into a variable, then we write a function to do the actual work. In the function, we set variables for the item, the item’s width and height, the width of the items direct container, the aspect ratio of the item, and finally we use the ratio to set a new height. Then we simply apply the new width and height to the item.
After the function is created, we create another function that applies the first one to our cache of iframes. Finally, we fire the second function on load and on window resize. Boom! Responsive iframes.