How To: Use FitVids.js with WordPress for Responsive Videos

16th April 2014

Let me set the scene. You’ve got a great responsive layout, you’ve tackled the navigation menu and your typography all looks spot on even when you view it on your iPad mini. Then you go to insert a video in your blog and you realise that it’s shooting out somewhere into oblivion. Nuts.

Thankfully some decent chaps have come up with a solution for that, which you can integrate into any WordPress theme with relative ease. It’s called FitVids.js, and it’s a jQuery plugin which will make all of your video embeds magically responsive. Here’s how you get it working:

Step One: Download FitVids.js

Go download the FitVids.js script fromĀ https://github.com/davatron5000/FitVids.js

Once you’ve done that, you’ll need to put it somewhere in the folder for your theme. Many will already have a ‘js’ folder which is a good place to copy it. Otherwise you could create your own, or see where the other scripts are stored.

Step Two: Enqueue the script

Next you need to call the script, which is best done using wp_enqueue. I wrote a whole post on how to do this correctly, called ‘How to: Correctly Include JavaScript Files in WordPress Themes‘.

Basically this is what you’re going to want to put in your functions.php file:

We’re registering the script and then enqueuing it in the front end of the site, but not in admin.

NB: Because FitVids is a jQuery plugin you’ll see that you need jQuery running for it to work. If your theme isn’t already loading jQuery, you can add it yourself by placing this above wp_register_script:

Step Three: Target the video container

The last step is to target your video container. The script as per the example on GitHub looks like this:

Seeing as we’re working with WordPress we’re going to need to modify this ever so slightly. We’re also going to want to go back to our functions.php file and call the script correctly in wp_footer rather than simply copy and pasting it into one of our other template files.

The final script to paste into functions.php is this:

The last thing to say is of course that #things-with-videos needs to be changed to reflect the container that holds your videos. On this site that means setting it to .post but it may also be, for example, .entry-content. You need to refer to your theme files to see what your post content is wrapped in.

Example

I’ve included a video of Sarah Jarosz being brilliant so that you can see FitVids.js in action.

Jo is a very rare person. She has the technical know how to build you a beautiful website in the blink of an eye, but more importantly, (unlike most techie types), she can explain everything about the process in simple layman’s terms. As a result, the process of designing and managing your website is completely stress free. Her charges are very reasonable too. Thank you, Jo.

Emma Kemp