jQuery to Resize Videos
by c.bavota | Posted in Tutorials | 7 comments
When WordPress introduced post formats in version 3.1, I decided to make sure all of my themes were able to display each one. The only issue I encountered was with videos. Not all browsers excepted setting a specific width and an auto height using CSS, so I had to develop a little bit of code using jQuery to make sure that all the videos that were displayed on the index page or the archive pages displayed in the correct aspect ratio.
This is the piece of jQuery code that I now include in the footer of all of my themes:
$("object, embed, .format-video iframe").each(function() {
var orig = $(this);
var ratio = orig.attr("height") / orig.attr("width");
var parWidth = orig.parents().find("p:last").width();
if(orig.attr("width")> parWidth) {
orig
.attr("width", parWidth)
.attr("height", (parWidth * ratio));
}
});
This code finds every video and checks to see what the parent containers width is. It then resizes the video to the correct size and aspect ratio so that it doesn’t exceed the boundaries of the parent container. You can see it working on the front page of the Magazine Premium demo.



This is awesome, going to put the to use in my new WordPress plugin. Just note the new changes in jQuery 1.6.x and the change from
.attr()to.prop().I modified it just a bit:
$('iframe#youtube-embed').each(function() { var ratio = $(this).height() / $(this).width(); var parent = $(this).parents().width(); $(this).css('width', parent); $(this).css('height', (parent * ratio)); });Greetings from Russia!
Thank you!
Good work!
Thank- you, thank-you, thank-you! This is exactly what I spent an hour trying to code myself last night and it works beautifully.
This is a brilliant approach that I look forward to implementing. Thanks!
Thanks for sharing! This is a pretty useful bit of code for sites with fluid layouts. It works like a charm on vimeo embeds! If you wrap it in a function you can also make it resize the videos any time someone changes their browser size with an .addEventListener. I use it like this on one of my wordpress sites:
function videoautoheight(){ $("object, embed, .format-video iframe").each(function() { var orig = $(this); var ratio = orig.attr("height") / orig.attr("width"); var parWidth = orig.parents().find("p:last").width(); if(orig.attr("width")> parWidth) { orig .attr("width", parWidth) .attr("height", (parWidth * ratio)); } }); } videoautoheight(); window.addEventListener('resize', videoautoheight, false);sorry that should be “if(orig.attr(“width”)> parWidth)”