Categories
Responsive Design Tutorials WordPress

Automatic responsive videos in WordPress with oEmbed, FitVids and a little PHP magic

Automaitc responsive videos in WordPress with oEmbed, FitVids and PHP
UPDATE: I’ve added a 4th step to the list to remove automatic inline styles from being inserted when embedding videos.

If you’re using a responsive theme on your WordPress site (or you’ve built a responsive theme) and you’ve added YouTube, Vimeo or other videos using oEmbed you will undoubtedly have noticed those videos do not resize with the rest of the frame. And that’s a royal pain. Fortunately there are solutions out there that can fix this, but they are a little tricky to implement. In this tutorial I’ll share with you a method for making the process automatic so you don’t have to worry about it.

The Problem

Responsive themes use percentage values, media queries and other coding magic to make the content resize to fit the size of the window. But when you embed videos from YouTube etc using the built in oEmbed function in WordPress (i.e. just paste in the URL to the video and it appears automatically) that video is inserted with a fixed width and height. As a result when the rest of the page resizes to fit the window, the video stays the same size causing all sorts of problems. This is sub optimal.

FitVids to the rescue… almost

Realizing this is a frustrating problem Chris Coyier and Paravel created a clever little jQuery plugin called FitVids that when installed automatically resizes videos along with the rest of the content. FitVids attaches to specified containers and forces the video iframes within these containers to resize along with it. Very clever and it works exactly as expected. However, to make this work you have to wrap the video in a container with a specified class. So if you want to use the oEmbed method you have to go to HTML view, create a div with a class and then put the URL inside it. Which kind of takes away the whole point of using oEmbed which is simplicity.

The Solution

What is needed is a function that automatically wraps all oEmbed videos in a div with the correct class that applies FitVids so all the user has to do is paste in the link to the video and then WordPress does the rest. And that’s just what we’re going to do:

Step 1: Enqueue FitVids

Go download FitVids.js from GitHub and add the jquery.fitvids.js file to your theme. I place all my JavaScript files in a sub-folder called ‘js’ for simplicity. Then we need to enqueue the script and associate it with jQuery. This is done in functions.php:


<?php 
// Add FitVids to allow for responsive sizing of videos
function your_theme_fitvids() {
	if (!is_admin()) {

		wp_register_script( 'fitvids', get_template_directory_uri() . '/js/jquery.fitvids.js', array('jquery'), '1.0', true);    	
		wp_enqueue_script( 'fitvids');
	}
}

add_action('init', 'your_theme_fitvids');
?>

This function loads the jquery.fitvids.js file along with the packaged version of jQuery that comes with WordPress whenever a page is loaded.

Step 2: Create a function to target the videos

To make FitVids work you need to add a JavaScript function targeting a specific class. The function looks like this:


<?php
add_action('wp_footer', 'add_fitthem');
    	
function add_fitthem() { 
	    	jQuery(document).ready(function() {
    			jQuery('.video').fitVids();
    		});
}

All that happens here is the action is loaded in the footer (so it doesn’t slow down the population of the page itself and allows the videos in the iframes to load properly). It then appends the function to the .video class so that any video inside a div with the class video will be scaled to size.

This function is combined with the previous function so they get called at the same time. The resulting function looks like this:


<?php
// Add FitVids to allow for responsive sizing of videos
function your_theme_fitvids() {
	if (!is_admin()) {

		wp_register_script( 'fitvids', get_template_directory_uri() . '/js/jquery.fitvids.js', array('jquery'), '1.0', true);    	
    	wp_enqueue_script( 'fitvids');
    	add_action('wp_footer', 'add_fitthem');
    	
    	function add_fitthem() { 
		    	jQuery(document).ready(function() {
	    			jQuery('.video').fitVids();
	    		});

	    }
	}
}

add_action('init', 'your_theme_fitvids');

Step 3: Automatically wrap oEmbed videos in a div with a class

The last step is to change the oEmbed output so that it automatically wraps the video iframe in a div with the class .video. This is done using a filter:


<?php
// Automatically add FitVids to oembed YouTube videos
function your_theme_embed_filter( $output, $data, $url ) {

	$return = '<div class="video">'.$output.'</div>;
	return $return;

}
add_filter('oembed_dataparse', 'your_theme_embed_filter', 90, 3 );
?>

This function grabs the output of the oembed_dataparse function (the one that creates the final code when you paste in a video URL) and wraps it in the correct div.

Step 4: Set Maximum Embed Size to 0

To get everything to work properly you have to go to Settings -> Media and set both width and height under Maximum Embed Size to 0. If you have a value in either of these fields, WordPress will include inline style code to constrain the size of the video and as a result the automatic resizing will not work.

That is all! When you add new videos to posts and pages using the oEmbed function, they are not automatically wrapped in the correct div and class and FitVids is applied. And voila: Your videos are responsive.

Caveat: These functions are not recursive!

The only catch with this process is that it is not recursive. By that I mean it doesn’t automatically work on videos that have already been embedded on your site. That is because the oembed_dataparse() function is called the when the post is published or updated. As a result, the function has already been run on old content and to apply the new div and class you have to re-run it. Fortunately that just means going in and clicking the Update button for each of the posts that have oEmbed videos in them, but if you have hundreds of videos you may want to consider doing some sort of database search/replace action.

To avoid the recursive problem I suggest you add this function to your theme at the very beginning and be done with it. That way as you populate your site the all your videos will be responsive.

Comments? Questions? Problems?

Got something to say? Leave a comment below.

Categories
Book Reviews CSS HTML

Book Review: Handcrafted CSS: More Bulletproof Web Design

Some context: People keep asking me what books they should read to learn about web design and everything else under the sun. Therefore I’ve decided I’m going to start reading books about web design and everything else under the sun and write reviews of them so you can see if it’s a book you should check out too.

The One Sentence Review

Handcrafted CSS: More Bulletproof Web Design is a book by and for web designers and developers with a solid understanding of HTML and CSS who want to push things further with standards-based code and progressive enhancements through CSS3 and other bleeding edge technologies.

The author(s)

Handcrafted CSS: More Bulletproof Web Design has one of those weird author listings on the front cover: Dan Cederholm with Ethan Marcotte. If you’ve watched the movie Julie and Julia you know that “with” means that the majority of the book is written by Cederholm while a smaller portion is by Marcotte. For this book I’d say the book itself is by Cederholm and that it features an essay by Marcotte that brings in a slightly to the left but still highly relevant aspect that elevates its overall quality and usefulness.

Dan Cederholm is the man behind Simplebits.com and author of the famous book Bulletproof Web Design of which the last edition was published in 2007. I have not read that book and by now I have a feeling it is too outdated to invest in. I might pick it up at the library but it’s doubtful. But people I know and trust say it’s a great book so I’ll make that assumption. Cederholm has created some truly impressive websites over time, many of which you have probably visited, and he’s one of those people who not only knows what he’s doing and does it better than most but also knows how to communicate that knowledge to others so they can step in his footprints rather than stake out their own way through the wilderness.

Ethan Marcotte is the man behind UnstoppableRobotNinja.com and he pops up as the co-author of several books including Designing with Web Standards which is one of the next books on my long list of things to read. Like Cederholm Marrcotte has worked on some pretty impressive projects over the years and his understanding of how the web works is hard to rival, even for Cederholm.

Both these gentlemen are at the very forefront of web design and development where standards and best-practices are concerned. As such this combo bodes well for the book they’ve collaborated on.

The Book Itself

Excluding front and index matter and preface Handcrafted CSS: More Bulletproof Web Design is a fairly short book of 204 pages. It’s in an unusual square-ish shape and comes in full colour with a nice and easy-to-read page layout. Considering the length of other books on the same subject matter it’s easy to think this book to be a little too light on material and substance. That would be a big mistake. These pages are heavy on real-world examples and applications with very little filler text. Although it has the sub-title “More Bulletproof Web Design” the book does not work as an extension of the original book but rather as an appendix. In other words it stands on its own. As a designer/developer with a firm understanding of HTML, CSS and all that surrounds these two code languages I found the book to be an engrossing and immersive read with bucketloads of valuable input. But I can see that without such a solid platform to stand on I would have judged the matter as both superficial and overtly simplistic. Which is the surprising consequence of Cederholm and Marcotte’s clean-and-simple approach.

Having worked with web design and development for many years I’ve noticed that as my understanding and skill set improves, my code becomes more and more simplistic and clean while the end result of that same code becomes more advanced. Handcrafted CSS latches onto this by providing even more simplistic and cleaner code examples and solutions to create well functioning and æsthetically pleasing websites. This is a huge benefit if you’re well versed in web code and a devestating detrement if you’re just starting out: If you don’t have a firm grasp on the code and understand what Cederholm and Marcotte is trying to do this book will seem like a series of disjointed code examples that at the same time go in too much detail and skim over the important stuff.

Futureproofing, progressive enrichment and clearing floats

Cederholm’s portion of the book concerns itself with three major elements:

  • Futureproofing
  • Progressive enrichment through CSS3 (in particular rounded CSS corners, RGBA colours and drop-shadows)
  • A better model for handling floats and clears

These are all hugely important considerations as both the web and the devices we ingest it on evolve but they are easily overlooked because they seem peripheral or subordinate to the issue of getting the content out and working properly.

Cederholm’s approach (and the root of the name of the book) is that a craftman goes the extra mile to add often invisible but still vital elements to her creations to make them stand out. Those elements, or enrichments, can be anything from a properly wrapping list item to a custom ampersand symbol, a gracefully degrading rounded corner or just introducing a semantically sound solution to float and clear management.

FYI: If you’re considering buying this book and the sentence above made you shake your head or think “what the hell is he talking about” I would recommend getting something else instead.

To me Cederholms chapters were divided evenly between verification, a-ha moments and new information. His approaches to futureproofing – making sure that designed elements are able to handle content that goes beyond the original drafts (i.e. a button with text that spans more than one line or has long words in it) – are ones I have strived to live up to even before reading the book. Thus seeing him applying the same philosophies and techniques in his QA process was a verification that I am on the right track. When I started on the section on a semantic solution to floats and clears and saw his ingenious .group solution I was left thinking “What the hell have I been doing all this time? This makes way more sense!” Needless to say the lessons learned from these chapters are now being implemented in all my current and future projects. And as I worked my way through the CSS3 examples and Cederholm’s pragmatic “progressive enrichment” approach I gained confidence and found a desire to start incorporating drop shadows, RGBA colours and rounded corners in my designs now rather than wait for all the browsers to get with the program.

Actually, Cederholm’s attitude toward progressive enrichment deserves special mention here. Whereas a large majority of web professionals have made Internet Explorer bashing into a competitive sport Cederholm proposes a more pragmatic approach: Rather than designing for cutting edge browsers and being frustrated by older browsers not keeping up he creates designs that incorporate rewards for more forward-thinking browsers while incorporating clean and simple solutions for the older generation. This is the only reasonable approach and one I’ve been promoting myself for years so it’s good to see I’m not standing alone on this.

The Fuid Grid

Although Ethan Marcotte’s contribution to the book is only a singular chapter it is a hugely important one. As the title suggests it concerns, and solves, what has been a bit of a mystery for many: The Fluid Grid. Grid-based layouts have been a pillar of print design since the early 1920s and have started making their way onto the web. There are many reasons for this, none of which I will cover here. The challenge with grids on the web has always been that they are either entirely static or at the very least have static elements. This becomes a problem when visitors use devices with unusual or small screen sizes (think a phone, an iPad or a vertically oriented screen) because they are often forced to scroll left and right to access the information on the screen. Marcotte sets out to create a proper fluid grid layout and manages quite well through the use of relative sizes like em and % combined with a fair bit of math. The resulting fluid grid is quite ingenious and introduces flexibility to sites that previously were confined to rigid structures. And practicing what they preach both Marcotte and Cederholm use these types of fluid grid layouts on their own sites. Open them and resize your window to see for yourself.

The Bottom Line

The red line running through Handcrafted CSS: More Bulletproof Web Design is the attitude that a little extra refinement and forethought will bring rewards, in functionality, æsthetics and simplicity. And this attitude is one that can be applied to pretty much every aspect of life, not just web design. Cederholm and Marcotte are both living examples of how well this approach works and their sites stand as testaments to the techniques and parctices.

This book is for the seasoned designer / developer who already has a firm grasp on HTML and CSS but wants to take it further. It is also an excellent introduction to the world of CSS3 and fluid grid layouts for those that want to push their sites and designs into the future. The book is best read while sitting in front of your computer, preferably with a project on hand where the techniques can be implemented immediately. It is when you see the examples take shape and improve your own designs you realize where the value lies in this book. It’s not as much a list of good code examples as a guide to improving your own work. As such the seemingly disjointed code examples actually make a lot of sense: Rather than presenting pre-packaged functional content they are laid out in such a way that they can be slotted into pretty much any project for instant effect. This falls well in line with the theory that new knowledge is best retained when immediately applied to something that matters to the person learning it.

I wholeheartedly recommend this book wihtin the parameters I just set out and look forward to learning more from both Cederholm and Marcotte.

Categories
Expression Web My Book News

Breaking the silence: What I’ve been doing over the summer

If you follow this site and my Tweets you will surely have noticed my relative silence over the summer. Well, there is a reason… more precicely 3 reasons. I’ve been colossally busy dealing with three major projects that as of now are either nearing completion or at a point where I can start focusing on other stuff (like long neglected clients) again. So, to stave off the criticism for my falling off the face of the internet here’s a taste of what I’ve been working on:

Sams Teach Yourself Microsoft Expression 4 in 24 Hours

Earlier this summer Microsoft released version 4 of Expression Studio. The new version brough major upgrades to Expression Web and as a result my hugely popular book Sams Teach Yourself Microsoft Expression Web 4 in 24 Hours had to be updated. That meant I had to go through every nook and cranny of the new version to find all the new goodies, come up with new examples to show them off and then rewrite whole chapters to reflect these changes. It may come as a surprise, but revising a book like this is almost as much work as writing it from scratch. Which means once v5 comes out I am likely to do a complete rewrite. But that’s a different story.

The new book, scheduled to be released end of October, features updated and extended examples, new features, removal of deprecated features. New content worth noting is an extended chapter on the new and improved Expression Web SuperPreview which now includes full support for IE6, 7, 8 (compatibility mode) and 8 as well as a new feature called Remote Browser Testing that allows for testing on external browsers like Safari for Mac and an entire chapter on the new Search Engine Optimization (SEO) Checker tool.

Expression Studio 4 and Expression Web 4 comes as a free upgrade if you already own version 3. That means if you have version 3 you should upgrade right away. And if you alredy have my version 3 book you should get the new version once it comes out. I’m not saying this because I want to sell more books but because there are some new features in there that are important to understand and get the full use out of.

Microsoft Expression Web 4 LiveLessons (Video Training)

In addition to the book I’ve also created a colossal 27 lesson video series clocking in at around 5 hourscalled Microsoft Expression Web 4 LiveLessons (Video Training) for those of you who either don’t want to read a book or who want more hands-on training using Expression Web. The LiveLessons series features an entirely new example project based on the 12×12 Vancouver Photo Marathon website and provides a best-practice model for how to create professional, rock solid and stylish websites using standards-based HTML and CSS. The LiveLessons series is complementary to the Sams book so there are things that are covered in the videos that are not covered in the book and vice versa. Thus even though you’ll get a lot out of each item alone you’ll get a much better and more in-depth understanding by getting them both. Again, this is not a sales pitch – I’m being honest here. The combo really is the better deal.

The video series will be available on DVD early October and I believe it will also be available for download or online viewing on InformIT’s website (tba).

12×12 Vancouver Photo Marathon 2010

Because I don’t already have way too much on my plate I decided to start a huge photography event/contest last year called the 12×12 Vancouver Photo Marathon. In a nutshell it’s a contest where 60 photographers show up on a set date, pick up a 12 exposure 35mm film and then at the top of every hour for 12 hours are given one theme to interpret in one photo. At the end of 12 hours the films are returned, developed, judged and finally put up in a huge exhibit. In the end we end up with 720 photos divided into 60 sequences of 12 consecutive themes. The 2009 event was a massive success with over 300 people showing up for the gallery exhibit and we expect this year’s event to get even bigger.

In the runup to the even (and to kill two birds with one stone) I developed a new site for the marathon and used this site as the demo project for the Expression Web 4 LiveLessons series. As a result the site features some pretty fancy elements like a transparent CSS-only drop-down menu with multiple in-button styles, CSS3 drop-shadows and rounded corners and tons of other fancy schmancy style elements.

The 2010 12×12 Vancouver Photo Marathon takes place on Sunday September 12 from 8am to 8pm in downtown Vancouver with a home base at Blenz Coffee in Yaletown. Tickets for participation (60 in all) are $24 per person and cover all expenses. Tickets go for sale Thursday, August 12 at 8pm and are expected to sell out fast. The following art exhibit will be held at Vancouver Photo Workshops on the 16th of October.