jQuery to Resize Videos

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.

Share this:

Email
Facebook
Twitter
Pinterest
Pocket

Premium Themes for WordPress

Looking for an easy-to-use Premium Theme for WordPress? Check out Themes by bavotasan.com and have your site up and running in no time.

Use this WordPress website builder to build powerful websites in no time for your or your clients.

WordPress Hosting

WP Engine – designed from the ground-up to support and enhance the workflow of web designers.

Bluehost – providing quality web hosting solutions since 1996.

About the author

Picture of Luke Perrie

Luke Perrie