I have an iframe of a video inside a div, like so:
<div class="media">
<iframe>
</div>
I set the DIV's size dynamically on window resize.
I want to scale the iframe to fit inside the div, while maintaining it's aspect ratio. Most of the code out there deals with scaling images, which is easier.
This is what I have so far, but it doesn't work:
jQuery.fn.fitToParent = function()
{
this.each(function()
{
var width = jQuery(this).width();
var height = jQuery(this).height();
var parentWidth = jQuery(this).parent().width();
var parentHeight = jQuery(this).parent().height();
if(width < parentWidth)
{
newWidth = parentWidth;
newHeight = newWidth/width*height;
}
else
{
newHeight = parentHeight;
newWidth = newHeight/height*width;
}
jQuery(this).css({
'height' :newHeight,
'width' :newWidth'
});
});
};
Basically, I'm looking to replicate the sizing that "background-size: contain" does for images in CSS, but for an iframe in a DIV.
Thanks for the help!
I have really improved on the answer from @TrueBlueAussie over time, and thought I'd post a more sophisticated answer here for future reference.
Made it a plugin on GitHub here: https://github.com/drewbaker/fitToParent
Here is the jQuery plugin:
So, assuming you have HTML of this:
The most basic way to call the plugin is like this:
But I'll often set #wrapper to be close to window height and width, like this:
You can also feed in a custom box size to fit the element in, like this:
I've also added the ability to set a CSS class of "size-parent" to a parent element, and it will then use that parent element for the box size. A full example of that:
If you don't set a .size-parent, it will fallback to the element parent. If you set the box_height/box_width parameter, then those override everything obviously.
Now, to show how powerful this can be, try this for a vertically centered, horizontal centered aspect ratio correct iFrame!
In real life, I wrap the jQuery in a function, and then call that function on window resize for true responsive iFrames!
here:
http://jsfiddle.net/fFTS8/
Three issues noted:
You have an error (trailing quote) in your example:
:newWidth'
You need to set the iframe actual height and width attributes and not the style. Styling an iframe size has no effect:
the calculation for aspect ratio was wrong (needs to compare ratios to see which way they overlap). Without this not all overlap cases are catered for.
I also cleaned up the code a little to speed up element access. Each call to jQuery(this) costs cycles.
JSFiddle here: http://jsfiddle.net/TrueBlueAussie/ZJDkF/8/
Updates:
The jsfiddle now has examples of the 4 different scenarios of overlap and each retains the proportions of the iframe. I also added the window resize you mentioned and made the first div resize dynamically with it to demonstrate.