Responsive video

We have seen that, as ever, supporting older browsers leads to code bloat. What began with the <video> tag being one or two lines ended up being 10 or more lines (and an extra Flash file) just to make older versions of Internet Explorer happy! For my own part, I'm usually happy to forego the Flash fallback in pursuit of a smaller code footprint but each usage case differs.

Now, the only problem with our lovely HTML5 video implementation is it's not responsive. That's right. All that hard work and our responsive web design doesn't err… respond. Take a look at the following screenshot and do your best to fight back the tears:

Responsive video

Thankfully, for HTML5 embedded video, the fix is easy. Simply remove any height and width attributes in the markup (for example, remove width="640" height="480") and add the following in the CSS:

video { max-width: 100%; height: auto; }

However, whilst that works fine for files that we might be hosting locally, it doesn't solve the problem of videos embedded within an iFrame (take a bow YouTube, Vimeo, et al). The following code adds a film trailer for Midnight Run from YouTube:

<iframe width="960" height="720" src="http://www.youtube.com/embed/B1_N28DA3gY" frameborder="0" allowfullscreen></iframe>

Despite my earlier CSS rule, here's what happens:

Responsive video

I'm sure DeNiro wouldn't be too happy about this! There are a number of ways of solving the issue, but by far the easiest I have come across is a small jQuery plugin called FitVids. Let's see how easy it is to use the plugin by adding it to the And the winner isn't... site.

First of all, we'll need the jQuery JavaScript library. Load this into your <head> element. Here, I'm using the version from Google's Content Delivery Network (CDN ).

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>

Download the FitVids plugin from http://fitvidsjs.com/ (more information on the plugin is at http://daverupert.com/2011/09/responsive-video-embeds-with-fitvids/).

Now, save the FitVids JavaScript file into a suitable folder (I've imaginatively called mine "js") and then link to the FitVids JavaScript in the <head> element:

<script src="js/fitvids.js"></script>

Finally, we just need to use jQuery to target the particular element containing our YouTube video. Here, I've added my Midnight Run YouTube video within the #content div:

<script>
  $(document).ready(function(){
    // Target your .container, .wrapper, .post, etc.
    $("#content").fitVids();
  });
</script>

That's all there is to it. Thanks to the FitVid jQuery plugin, I now have a fully responsive YouTube video. (Note: kids, don't pay any attention to Mr. DeNiro; smoking is bad!)

Responsive video

Phew, all fixed. That should keep me on Bobby's Christmas card list!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.152.58