Setting up responsive video on a multi-author blog
Posted on

Thought I was doing some smart codin’ but… then the website brokeĀ
OK, all jokes aside. Recently I was building a site for a new online music magazine. Amongst the many things I needed to plan out, responsive video was one. I was using Zurb’s Foundation 4 to build a prototype of the site, so ofcourse I used their Flex Video built in classes.
Foundation ships with their own CSS for responsively displaying video on your site. Just add .flex-video to the wrapper, here’s the CSS:
|*|-css-|*|
.flex-video {
position: relative;
padding-top: 1.5625rem;
padding-bottom: 67.5%;
height: 0;
margin-bottom: 1rem;
overflow: hidden; }
.flex-video.widescreen {
padding-bottom: 57.25%; }
.flex-video.vimeo {
padding-top: 0; }
.flex-video iframe,
.flex-video object,
.flex-video embed,
.flex-video video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
Once in WordPress, I set up custom fields for placing the video iframe code. In the template, I prefixed and suffixed the custom field with their necessary markup. Note: I’m using the highly admired plugin Advanced Custom Fields for creating the custom fields UI in the backend, and code for conditionally displaying in theme.
|*|-php-|*|
<?php
if(get_field('video'))
{
echo '<div class="flex-video">' . get_field('video') . '</div>';
}
?>
So great, if an video is included in the post in the designated custom field spot, responsive it will be.
So what did they do?
Authors starting dumping the embed code right inside WP’s main content section, which was not what my intention was… This made me realize that authors and users are going to use this software the way that best makes sense to them, not me.
To fix this I simply included a small script that would add the class to any iframe inserted in the post.
|*|-javascript-|*|
<script async>
$(document).ready(function(){ // Add flex class to iframes inserted into the content
$('section.post_content iframe').parent('p').addClass('flex-video');
});
</script>