Rey Bango

JavaScript, HTML, CSS & Random Stuff…

Presenting at the jQuery Summit Online Conference on November 17th

Next week, Environments for Humans will be hosting their 2nd jQuery Summit Online Conference and what a great event it will be. The speakers (myself included) are just an who’s-who of the jQuery world so you can be sure to get awesome presentations during the event. Lined up are experts like:

  • John Resig
  • Jonathan Snook
  • Richard Worth
  • Emily Lewis
  • …and a lot more.

The event is divided into two tracks targeting designers on the 16th and developers on the 17th. I’ll be presenting on the 17th and will be discussing how to use the new jQuery Templates plugin to make code layout much easier.

You can register for the event by going to the jQuery Summit website and when you do, be sure to take advantage of the following code for a 20% discount on your registration: JQUERY2010

The great thing about this is by registering, you’re also helping out the jQuery project as Environments for Humans is donating part of the proceeds of the conference to the jQuery Foundation.

I’m looking forward to this event and I hope to see you there as well!

Something Just Came Over Me…

I did an interview with James Senior on Microsoft’s Channel 9. We chatted about Script Junkie, the site I manage for Microsoft. We also chatted about the jQuery conference and how awesome it was going to be. Then, in the last 30 seconds of the interview, something just came over me. Well, Ralph Whitbeck though it would be awesome to create a video of that “special part” and air it to the jQuery Conference attendees. Here is his handy work:

How Polyfills “fill in the gaps” to make HTML5 and CSS3 Usable Today

There’s been a lot of commotion over the last week since the W3C announced that HTML5 is not ready yet for deployment to websites. Some really smart people have weighed in on this topic and I agree with their thoughts. Last Thursday, I did a presentation on the new features of HTML5 and part of that was demonstrating how polyfills work to allow you to leverage these new features while still providing a good cross-browser experience.

What’s a Polyfill?

I really love Paul Irish’s definition since it sums it up perfectly:

polyfill: A shim that mimics a future API, providing fallback functionality to older browsers.

The basic premise is that most older browsers may not have all of the features of the HTML5 and CSS3 specifications and they need a helping hand to make them provide a good user experience. A great example of this are the new HTML5 semantic tags like <article>, <section>, <header> & <nav> which render fine in all major modern browsers like IE9 beta, Firefox, Chrome, Safari & Opera but lack support in popular browsers like IE6 through IE8.

So for my demo, I decided to create a simple page that showed a blog-like layout using these new tags while ensuring that they can still render correctly in IE8. Here’s the layout code I used.

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Rey's Awesome HTML5 Blog</title>
    <meta name="description" content="" />
    <meta name="keywords" content="" />
    <meta name="author" content="" />
    <meta name="viewport" content="width=device-width; initial-scale=1.0" />

    <!-- !CSS -->
    <link href="css/html5reset.css" rel="stylesheet" />
    <link href="css/style.css" rel="stylesheet" />

</head>

<body>

	<header>
        <h1>Rey's Awesome HTML5 Blog</h1>
	</header>

    <nav>
    	<ul>
			<li><a href="#">Home</a></li>
			<li><a href="#">About</a></li>
			<li><a href="#">Contact</a></li>
		</ul>
    </nav>

	<section>

        <header>
        <h1>Rey's Blog Posts</h1>
	    </header>

        <article>
            <header><h1>The In's & Out's of HTML5</h1></header>
		    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing  elit. Fusce vitae orci. </p>

            <footer>
                October 7, 2010 - comments( 0 )
            </footer>
        </article>

        <article>
            <header><h1>HTML5 Ate My Lunch</h1></header>
		    <p>Fusce vitae orci. Lorem ipsum dolor sit amet, consectetuer adipiscing  elit. </p>
            <footer>
                October 5, 2010 - comments( 3 )
            </footer>
	    </article>		

	</section>

	<footer>
		<p>Copyright Rey Bango, 2010</p>
	</footer>

</body>
 </html>

I used a HTML5 reset style sheet because unfortunately, most browser don’t have an internal style sheet that sets the expected behavior for specific elements. For example, you would expect an <section> element to be block level but due to a lack of the internal browser style sheet, it renders inline.

Then, I added the styles I needed to get my page to look the way I wanted:

/* Global */
body { font-size: 16px; font-family: arial,helvetica,clean,sans-serif;  }
a { color : #33CC33; }
a:hover { text-decoration: none; }

/* Header */
header h1 { font-size: 48px; }

nav { overflow: auto; margin-bottom: 25px; }
nav li {float:left; padding-right: 5px; }

/* Main Content Area */
section { width: 500px; font-size: 12px; }
section h1 { font-size: 16px; }

article { background: #CCCC99; margin-bottom: 10px; padding: 5px; -moz-border-radius:10px; -webkit-border-radius:10px; border-radius:10px; }
article footer { text-align: right; margin-right:5px; }
article h1 { font-size: 12px; }

and when I tested it in Firefox 3.6.10, it looked exactly like I expected:

but look what happened when I tried to bring up the page in IE8:

None of the stylings were available because IE8 doesn’t recognize the new HTML5 elements. Further, in order to get IE6-8 to recognize these elements, you explicitly have to create the DOM nodes for them using JavaScript. The exact reason is unclear but it may be some type of parser bug. The following code needs to be in the <head> section of your page in order for the elements to be created and recognized by IE6-8:

document.createElement("header");
document.createElement("nav");
document.createElement("section");
document.createElement("article");
document.createElement("footer");

It’s a little bothersome to do that but it’s not a massive bit of code at least.

Enter Modernizr

The code I just listed to create your HTML5 elements is certainly useful but work has already been done to handle that for us via the awesome Modernizr JavaScript library. Not only does it act as a polyfill, creating these new elements for us automatically, but it offers a ton of detection capabilities for features of both HTML5 & CSS3. This allows you to determine how you will offer fallback support when a feature isn’t available.

Including Modernizr.js is incredibly easy since it’s only a one line script tag like this:

<script src="js/modernizr-1.5.min.js"></script>

As I mentioned, Modernizr is smart enough to determine when new semantic elements need to be created and will handle the dynamic creation of elements such as <article>, <section>, <header> & <nav> instead of you having to write JavaScript code to do it. So once I’ve added Modernizr to my page, I get the following results in IE8:

Now you’re probably looking at this screenshot and say, “Hey, you have no rounded corners!”. You’re right because I used the CSS3 border-radius property to create rounder corners for all of my <article> elements and IE8 doesn’t support that property. The important thing, though, is that IE8 now recognizes these new elements and allowed me to style them.

But What About those Rounder Corners?

Geez, you guys are so demanding! Okay, so the cool thing is that Modernizr offers detection of key features of HTML5 *and* CSS3 and with that, we can determine if something like border-radius is available and if not, using a new term coined by Alex Sexton, we’ll use “regressive enhancement” to provide similar capabilities for older browsers. In this case, we’re going to see if border-radius is available and if not, lazyload in Mike Aslup’s jQuery Corners plugin to fill in the gap:

    <!-- Load jQuery -->
    <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js" type="text/javascript"></script>

    <script type="text/javascript">
        // See if border-radius is available
        if (!Modernizr.borderradius) {

            // If not, then load in the jQuery Corners plugin and apply rounded corners to the article elements
            $.getScript("js/jquery.corner.js", function () {
                $("article").corner();
            });

        }
    </script>

Now, when the code detects that border-radius is not available, it will just use the Corners jQuery plugin instead and render the following in any browser that doesn’t support the property:

Download the Code

I hope this post has shown you how polyfills can allow you to use HTML5 & CSS3 today. While I respect the W3C’s desire to ensure that the HTML5 specification is up-to-snuff, I think it’s important to realize that developers are resourceful and professional enough to create best practices that allow us to build apps with these new features right now.

I would highly recommend reviewing this VERY BIG LIST of polyfills and shims which can provide much of the missing capabilities in older browsers.

If you’d like to play with the code directly, I’ve packaged it up in a .zip file and you can download it here:

Code for HTML5 Semantic Tags using Polyfill to Degrade Gracefully (.zip)

Want to Build Apps for Windows Phone 7? Get Free Training at Various Locations Nationwide.

I’m pretty excited about the new Windows Phone 7. I’ve used it several times and I have to say it is a VERY hot phone and I can’t wait to get mine. I just got word that Microsoft will be putting on events nationwide to help developers learn how to build applications for this new platform. Here’s the deal:

Experience two days of fast-paced learning and create high-demand applications with Windows Phone 7. First, you’ll go under the hood of Windows Phone 7. The next day, attend a hands-on app building workshop. Bring your best ideas and prepare to upload into the full-service Marketplace. Visit www.msdnevents.com/wp7 for details.

If you’re a mobile developer or considering jumping into the mobile space, this is a great opportunity to get great FREE exposure to Microsoft’s newest platform and get your apps loaded up onto the marketplace quickly.

How to Create HTML5 Website and Page Templates for Visual Studio 2010

Now that I work at Microsoft, I’m using Visual Studio 2010 as my main editor. By default, an empty web page is created with an XHTML 1.0 doctype and it’s pretty barebones. Since I’m focusing on HTML5 & JavaScript development, having to constantly update the page with references to the new HTML5 doctype, jQuery, Modernizr and all of the other tags I use for my pages was becoming a drag.

Today, I noticed a blog post by Zander Martineau in which he added a lot of HTML5 goodness to the Coda IDE in the form of clips, which is the code snippet format supported by Coda. This got me inspired to find out how to do something similar in Visual Studio, so I pinged Damian Edwards of the Visual Studio team for advice. He pointed me to the following article which explained how to create “Item Templates” in Visual Stuido.

The gist of it is that you can take any page that you create and turn it into a re-usable template via the “File->Export Template…” wizard. It walks you through the process of choosing a specific file or entire project/website to use as a template.

Adding a Page Template

So here’s the basic HTML5 template I wanted to include:

<!doctype html>
<html lang="en">
<head>
	<meta charset="utf-8" />
	<title></title>
	<meta name="description" content="" />
	<meta name="keywords" content="" />
	<meta name="author" content="" />
	<meta name="viewport" content="width=device-width; initial-scale=1.0" />

    <!-- !CSS -->
    <link href="css/html5reset.css" rel="stylesheet" />
    <link href="css/style.css" rel="stylesheet" />

    <!-- !Modernizr - All other JS at bottom
	<script src="js/modernizr-1.5.min.js"></script> -->

	<!-- Grab Microsoft's or Google's CDN'd jQuery. fall back to local if necessary -->
    <!-- <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js" type="text/javascript"></script> -->
	<!-- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> -->
	<script>	    !window.jQuery && document.write('<script src="js/jquery-1.4.2.min.js"><\/script>')</script>

</head>

<body>
	<div id="container">

	</div>
</body>

</html>

After I created and saved this page, I went to “File->Export Template…” and followed these steps:

Now, when I select “File->New File…” to add a new item, my template is available:

Adding a Web Site Template

Creating this page template was a huge help. I can now start with a fresh template that specifically works for my style of development but I didn’t want to stop there. I also wanted to create a skeleton that I could use as the basis for new websites and I wanted it to package all of the important files that I use from the get-go. In this case, I wanted:

  • My HTML5 basic page template
  • jQuery
  • Modernizr
  • HTML5 Reset CSS file
  • An empty CSS file called style.css
  • A consistent folder structure for all of these

The first thing I needed to do was to create a new website in Visual Studio. From there, I needed to create and/or organize all of the files that I wanted as the basis for my skeleton. Using the same Export Template wizard, I followed the following steps to create my project skeleton:

So now when I select “File=>New Web Site” I see my new template:

and when I choose that, here’s what gets loaded for my new site:

Download the Templates

Note: The templates in this article have been updated to support jQuery 1.5.1 & Modernizr 1.7. Check it out here.

This is a huge time-saver for me and I want to share this. I’ve made both templates available for download so you can drop them into Visual Studio yourself. Just grab the specific file and drop the zip into the folder I specified:

HTML5 Page Template

Drop this into “Visual Studio 2010 > Templates > ItemTemplates” folder

HTML5 Web Site Template

Drop this into “Visual Studio 2010 > Templates > ProjectTemplates” folder

How to Add Internet Explorer 9 Jump Lists to Your Site

With Internet Explorer 9 Beta is out, I’m poking around with some of the new features available. One of the new features called website pinning allows you to “pin” a website to your Windows 7 taskbar for easy access later. The pinning feature, in itself, isn’t really all that interesting to me because you could create desktop shortcuts to webpages for years. What is cool, though, is the ability specify direct links to important pages from a pinned website. These are called “Jump Lists” and they provide navigation capabilities straight from a pinned website. The obvious use case for this is to allow users to immediately reach the most important pages on a site without having to open the browser, type in the web address and click on several links to get to a page.

The code to make jump lists available is very straightforward. A new meta tag called “msapplication-task” is available in IE9 which allows you to define the navigation for your pinned website. For example, I added the following jump list to my blog:

and here’s the code I added to my site to make that happen:

<meta name="application-name" content="Rey Bango Front-end Developer"/>
<meta name="msapplication-tooltip" content="Launch Rey Bango's Blog"/>
<meta name="msapplication-task" content="name=About;action-uri=/about/;icon-uri=/images/about.ico" />
<meta name="msapplication-task" content="name=The Big List;action-uri=/the-big-list-of-javascript-css-and-html-development-tools-libraries-projects-and-books/;icon-uri=/images/list_links.ico" />
<meta name="msapplication-task" content="name=jQuery Posts;action-uri=/category/jquery/;icon-uri=/images/jquery.ico" />
<meta name="msapplication-task" content="name=Start Developing;action-uri=/category/javascript/;icon-uri=/images/script.ico" />
<link rel="shortcut icon" href="/images/favicon.ico" />

The content attribute allows you to specify the name, action and icon that you’d like to use for your jump list nav entry. Here’s a list of the available meta elements that you can use to format your jump lists:

Name Content
application-name The name of the shortcut. If missing, the document title is used instead.
msapplication-tooltip Optional text that is displayed as a tooltip when the mouse pointer hovers over the pinned site shortcut icon in the Windows Start menu or desktop.
msapplication-starturl The root URL of the application. If missing, the address of the current page is used instead. Only HTTP, HTTPS, or FTP protocols are allowed.
msapplication-navbutton-color The color of the Back and Forward buttons in the pinned site browser window. Any named color, or hex color value as defined by Cascading Style Sheets (CSS), Level 3 (CSS3) is valid. For more information, see Color Table. If this meta element is absent, the color is based on the shortcut icon.
msapplication-window The initial size of the pinned site browser window. Content sub-elements provide size as number N, separated by a semicolon.

  • width=N (minimum 800)
  • height=N (minimum 600)

Note that user action overwrites this value. Windows preserves the user-generated window size when the user changes the size of the window and then closes the instance.

I could further customize the pinned site shortcut with start URL, initial window size, and navigation button color using the following code:

<meta name="msapplication-starturl" content="http://blog.reybango.com/about/"/>
<meta name="msapplication-window" content="width=800;height=600"/>
<meta name="msapplication-navbutton-color" content="red"/>

What About Other Browsers?

Unfortunately, this feature is IE9-specific functionality and not available via other browsers or operating systems; only Windows. I really wish it was more portable because it’s a slick feature and I honestly don’t know if other browser makers could do something like this. Let’s see if they consider adopting this type of UX.

Screencast

To actually see how the pinning works and how jump lists appear, I created a screencast that explains the whole process:

Internet Explorer 9 Beta has Arrived! The Features that Matter to Me as a Developer.

Wow, I can’t believe this day has come! After so many years of developers wishing for a better browser from Microsoft, one that was more consistent with web standards and would allow them to develop cross-browser websites leveraging the same markup, today marks the day that developers finally have that browser; Internet Explorer 9 Beta. It’s an important day because this release, although just a beta, is the culmination of a lot of effort and most importantly, listening, by the Internet Explorer team.

While the Internet Explorer browser has enjoyed widespread adoption by consumers, it hasn’t always been viewed fondly by the development community. The important work of building cross-browser compliant websites has often been cumbersome, due in part to differing interpretations of browser APIs in previous versions of Internet Explorer. The differences forced developers, myself included, to find workarounds for functionality that, in many cases, had a clearly defined standard behavior.

HTML5, CSS3, DOM

With Internet Explorer 9, there’s been a concerted effort by Microsoft to focus on standards-based functionality that will ease cross-browser development while providing the features needed to build rich and immersive websites. Take, for example, IE9’s support for many of the features of HTML5 and CSS3, the specifications which are defining the future of the web. By including support for features such as Canvas, video, @font-face, CSS3 media queries, SVG and many others, we now have a rich base to provide more compelling experiences to end users. In addition, by ensuring that these features are conformant to the defined specifications, the sites we build should work with any browser that also supports those specifications.

To take it a step further, the IE team has enhanced the performance of many of the new HTML5 features by taking advantage of the GPU. This means that text, graphics and video will be substantially smoother and more responsive allowing websites to perform more like true applications.

And at the DOM level, important changes have been made to be consistent with the defined specifications making it easier to whittle down browser-specific code. For example, support for the W3C DOM Events specification (addEventListener & removeEventListener) in place of the proprietary IE model (attacheEvent & detachEvent) has been one of the most welcomed changes to IE9 as has the introduction of getElementsByClassName, supported for some time in the DOM Level 2 specification and now available in IE9.

JavaScript

Equally important is the performance boost provided by the new Chakra JavaScript engine which basically blows away older versions of Internet Explorer and brings IE9 in line with modern browsers such as Chrome, Firefox and Opera. JavaScript development continues to become more complex and intricate so the importance of these performance enhancements can’t be understated. The Chakra engine interprets, compiles, and executes code in parallel and takes advantage of multiple CPU cores when available and the results are obvious by the greatly improved benchmark scores from the Webkit Sunspider JavaScript Benchmarks.

Chakra JavaScript Engine – WebKit SunSpider Benchmarks

Updated Developer Tools

Substantial work has been done to update the Internet Explorer Developer Tools. The built-in tools, usually found by pressing F12, provided quite a bit of capabilities but were missing key components that were essential to effective testing and debugging of client-side source code. With this update, the tools now include a much anticipated network traffic inspector, Console tab, CSS editing, and an improved JavaScript profiler.

The new Console tab is a welcome addition providing the ability to inspect script easily as well as receive important page-specific error and warning messages.

IE Developer Tools – Console Tab

Of the new features, the one that I’m most excited about is the network traffic inspector, mainly because the bulk of my application development involves Ajax-based requests.

IE Developer Tools – Network Performance of Specific Assets

IE Developer Tools – Network Request Information

I can now do such things as determine load times of specific assets or inspect my request/response headers, cookies and return values without the need for breaking out of the browser to a 3rd party application such as Fiddler or Charles.

Get to Using it Today

A lot of effort has gone into making Internet Explorer 9 Beta a better browser. There’s certainly more work to be done but the fact that we now have a version of IE that provides standards-based functionality and allows us to use the same markup across browsers is pretty hot.

To really appreciate what you can build with IE9, though, you need to just start digging into it. Microsoft has created the following sites to give developers the knowledge and inspiration they need to leverage IE9 to its fullest:

  • Beauty of the Web – Explore all of the new features of Microsoft’s latest browser and check out the cool demos built using the advanced features of Internet Explorer 9 Beta
  • Internet Explorer 9 Test Drive – This site breaks down the new, advanced features of Internet Explorer 9 Beta and lets you get a visual of what’s possible with each bit of functionality
  • Internet Explorer Guide for Developers – The developer documentation you’ll need to learn how about the specifics of Internet Explorer 9 Beta

It feels great to know that we’re on a path to being able to build truly feature-rich websites that will be easier to maintain and provide a more exciting experience to users. While we’ll still need to support older browsers for some time, the fact that all the major browser vendors are heading in the same direction is going to allow us to build some truly amazing things. I can’t wait!

Using @font-face and Font Squirrel to Enhance Your Site with Fonts

I’ve been dying to check out @font-face and so I popped over to Font Squirrel to see what they offered. Originally, I thought it was going to be a paid service but the cool thing is that they offer 100% “free for commercial use” fonts! They even have some nice font kits already setup. The reason that the kits are great is because depending on the browser you’re using, you may need a different font format for the browser to render the font correctly. See, even though @font-face is being hyped up now in CSS3, it’s more of a standardization effort and not really a new feature. In fact, @font-face is supported in IE6. Seriously.

The basic premise is that you define the available fonts beforehand in your css file by declaring an @font-face rule. For example, I downloaded a font called “Arch Rival” and grabbed the whole kit because it included the font formats for every major browser as well as iPhone & iPad and I wanted to make sure they rendered correctly.

Typically, you would manually go into your CSS style sheet and enter a @font-face rule like this:

@font-face {
	font-family: 'SFArchRivalRegular';
	src: local('☺'), url('SF_Arch_Rival-webfont.eot');
	font-weight: normal;
	font-style: normal;
}

where src is the path to your physical font file. So yes, you can specify relative pathing for your font file like this:

src: url('fonts/SF_Arch_Rival-webfont.eot');

Once defined, you can now use the font’s semantic name to style a specific selector like this:

.post {
   font-family: 'SFArchRivalRegular';
   font-size: 18px;
}

This is fairly easy for a one-off type of deal but when you’re dealing with font that could have various rendering formats such as bold, italics, bold italics, extended italics, etc., entering all of this can become really tedious. If you don’t believe me, just check out the following style sheet. Font Squirrel takes the pain out of this.

When you download a font kit, you have a choice of downloading one big bundle with all of the necessary formats or using a font builder that allows you to select which format you’d like to use:

In my case, I chose everything and the really great thing is that the kit brought a pre-made CSS style sheet with all of the font definitions as well as a demo HTML file which included declarations that referenced the new font! This made it incredibly easy to get up and running quickly. If we look at the CSS style sheet declaration, we can see that the src property declares a number of additional formats for the Arch Rival font including the format() hint to define the format type:

@font-face {
	font-family: 'SFArchRivalRegular';
	src: url('SF_Arch_Rival-webfont.eot');
	src: local('☺'), url('SF_Arch_Rival-webfont.woff') format('woff'), url('SF_Arch_Rival-webfont.ttf') format('truetype'), url('SF_Arch_Rival-webfont.svg#webfontPgLtCzUx') format('svg');
	font-weight: normal;
	font-style: normal;
}

If we look at the demo page, we can see how the various font declarations affect the page.

So I decided to play a little more with some other fonts and pulled down a kit called “True Crimes“. I copied the font files into their own directory, updated the included style sheet to point to the right directory and then included the code into my blog.

@font-face {
font-family: ‘TrueCrimesRegular’;
src: url(‘/fonts/true-crimes-webfont.eot’);
src: local(‘☺’), url(‘/fonts/true-crimes-webfont.woff’) format(‘woff’), url(‘/fonts/true-crimes-webfont.ttf’) format(‘truetype’), url(‘/fonts/true-crimes-webfont.svg#webfontWTZyAk71′) format(‘svg’);
font-weight: normal;
font-style: normal;
}
h2.fontdemo {font: 60px/68px ‘TrueCrimesRegular’, Arial, sans-serif;letter-spacing: 0; }
[/code]

If you're curious about the multiple src property declarations, it has to do with IE and its support of the Embedded OpenType (.eot) font format, which no other browser supports. The declaration order ensures that IE will be able to find the right font file without falling over itself. Paul Irish has a nice explanation of the issue so be sure to read it.

Now, I can have a little fun whenever I want to by simply declaring an H2 header tag with a class of "fontdemo" and some text like this:

<h2 class="fontdemo">I'm digging @font-face!!</h2>

which gets me this:

I'm digging @font-face!!

A Bit of a Warning

Keep in mind that when you use @font-face in your site, you're now adding another HTTP request which could end up slowing down your page load. This is especially important to consider if you decide to use a remote font hosting service. Be sure to read Steve's thorough analysis of @font-face performance before going hog wild on your site. :)

An Update

Paul Irish pointed out the I had left out the local('☺') directive from the @font-face rule, which is really important in terms of performance since, as Paul wrote:

if it just so happens that a user actually has your custom font installed, this'll save them the download. The primary reason is that you cede control to the user's machine, potentially showing a locally installed font instead of the one you want to serve. While that will load faster, there's a very small chance the file could be wrong.

To account for this gotcha, I've specified a local font name of '☺'. Yes, it's a smiley face. The OpenType spec indicates any two-byte unicode characters won't work in a font name on Mac at all, so that lessens the likelihood that someone actually released a font with such a name. This technique is recommended if you think a locally installed version of this font is not in your best interest.

Also, because the local('☺') directive isn't supported it IE, it will simply ignore the second src declaration (which is for non-IE browsers) ensuring that you don't have an extra request that will issue a 404 and slow down your page's performance.

Thanks Paul!

Start Using CSS3 Pseudo-Classes in Internet Explorer 6, 7, and 8 using the Selectivizr JavaScript Library

Now that everyone is all giddy about CSS3 and all of the coolness it offers, lets get back down to earth. We still have older browsers to support so while using some of the new nifty features is definitely cool, we need to ensure we understand that at least 80% of web users won’t be on a cool new browser.

Enter Selectivizr, the Library Formerly Known as ie-css3.js

Internet Explorer is definitely one of those that needs special attention which is where a new library called Selectivizr comes in. It’s a JavaScript library that allows you to take advantage of CSS3 selectors now, even for users of Internet Explorer 6 through 8, by emulating these pseudo-selectors via JavaScript. It’s become such a hit that it was even nominated for Innovation of the Year in .net magazine’s 2010 awards.

The inclusion of Selectivizr is extremely easy. You add it in using a standard script tag just like any other JavaScript file. Notice that we’re using IE conditional statements to determine the browser version and if it’s less than IE9, the library gets included. Makes sense since IE9 should include many of these pseudo-selectors.

<script src="jquery-1.4.2.min.js"></script>
<!--[if lt IE 9]>
	<script src="selectivizr.js"></script>
	<noscript><link rel="stylesheet" href="css/ie-fallback.css" media="screen, projection"></noscript>
<![endif]-->
<link href="style.css" rel="stylesheet">

Once included, you’re now free to add CSS3 pseudo-classes to your style sheet. For example, I can now use the nth-child() pseudo-class to set the text to every odd numbered paragraph within my container div to red:

#container p:nth-child(odd) { color: #ff0000; }

and it will render correctly in Internet Explorer versions 6-8.

Check it out in Internet Explorer with Selectivizr NOT included.
Check it out in Internet Explorer with Selectivizr included.

In order to have done this previously, I would’ve have to had to rely on complex JavaScript or using methods included in a JavaScript library (e.g. jQuery’s nth-child method) to be able to grab the DOM element and style it. For example:

        $(document).ready(function () {

            $("#container p:nth-child(odd)").css("color", "#ff0000");

        });

Check out the jQuery version in Internet Explorer with Selectivizr NOT included.

While that will style the paragraphs the way I want, it’s not a portable and reusable solution. Using Selectivizr is substantially easier because I can now specify reusable CSS rules where they belong; in a style sheet.

The main thing that you NEED to have is a JavaScript library with a DOM selector engine. Selectivizr has support for jQuery, MooTools, Dojo, Prototype, YUI, DOMAssistant and the NWMatcher selector engine. Considering that most sites leverage at least one of these libs, that’s pretty good coverage.

One of the things I did notice when doing a view source on the Selectivizr website is something that I had already thought would be a good idea. The author, Keith Clark, combines his Selectivizr code with Remy Sharp’s html5shiv which makes a lot of sense considering html5shiv allows you style HTML5 tags in non-supporting browsers. So rolling up these two libs (or Modernizr) is a good idea. One less http request to make.

How Does this Work?

I pinged Keith so I can get a better understanding of the magic going on under the hood and here’s what he said:

Basically, the script scans the page looking for <link>‘d style sheets which are downloaded using a XmlHttpRequest (or ActiveX for IE6). The style sheets are then parsed for rules containing CSS3 selectors. Any matching rules are extracted and passed to a JavaScript library (such as jQuery, Prototype, NWMatcher etc.) which selects matching elements from the page. These elements are then given a unique className and, if necessary, event handlers are added (if interactive pseudo-classes such as :hover, :focus, : checked etc. need to be emulated). The original CSS rule is then replaced with the same className and once all rules are processed, the original style sheet content is replaced with the modified one.

So if you’re wondering why there’s a dependency on a JS lib, there ya go. For a deeper dive into the how-to’s check out his more thorough explanation here.

How to Easily Inject jQuery into any Web Page

I use jQuery…a lot. It just makes JavaScript development much easier for me. Every so often, I may come across a site where I want to poke around and see what’s going on under the hood. In many cases, jQuery is being used so it’s simple to spark up Firebug and leverage jQuery to work with a document. While jQuery is very pervasive, there are still plenty of sites that don’t use it which forces me to go back to plain ‘ole JavaScript. There’s nothing wrong with that but I’ve gotten used to the nice, terse syntax jQuery provides and I’d like to be able to use it.

Awhile back, I came across an awesome bookmarklet created by my jQuery teammate, Karl Swedberg, which allows me to inject the latest version of jQuery right into my page. This is great when you want to work with a page which doesn’t have jQuery included and you either don’t own the page or don’t feel like adding a script tag to it. The code below shows how the jQuery lib is included.

It’s fairly straightforward in that a script element is created:

var script=document.createElement('script');

and the script tag’s src attribute is set with the following URL:

‘http://code.jquery.com/jquery-latest.min.js’

Then, they grab a reference to the document’s head DOM element:

var head=document.getElementsByTagName('head')[0]...;

and then insert the new script tag into the head of the document.

head.appendChild(script);

That was a very high-level explanation because there’s definitely more going on. In fact, Karl took the extra step of ensuring that jQuery’s .noConflict() method is called should there be another library present that requires the “$” namespace. Very cool. :)

Now, this leverages the latest minified version from the jQuery repo but you should be able to easily include a version of jQuery from the Microsoft or Google CDNs if that’s your preference:

Microsoft: http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js
Google: http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js

You can find the full source for the bookmarklet below and if you want to install it now, here’s the link for you to use:

» jQuerify «– Drag this link to your browser toolbar

I created a quick screencast that shows you how to add the bookmarklet to your browser and then use it for playing with a web page:

Nicely formatted bookmarklet code:

(function() {
  var el=document.createElement('div'),
   b=document.getElementsByTagName('body')[0];
   otherlib=false,
   msg='';
  el.style.position='fixed';
  el.style.height='32px';
  el.style.width='220px';
  el.style.marginLeft='-110px';
  el.style.top='0';
  el.style.left='50%';
  el.style.padding='5px 10px';
  el.style.zIndex = 1001;
  el.style.fontSize='12px';
  el.style.color='#222';
  el.style.backgroundColor='#f99';
  if(typeof jQuery!='undefined') {
 msg='This page already using jQuery v'+jQuery.fn.jquery;
 return showMsg();
  } else if (typeof $=='function') {
 otherlib=true;
  }
  // more or less stolen form jquery core and adapted by paul irish
  function getScript(url,success){
 var script=document.createElement('script');
 script.src=url;
 var head=document.getElementsByTagName('head')[0],
  done=false;
 // Attach handlers for all browsers
 script.onload=script.onreadystatechange = function(){
   if ( !done && (!this.readyState
     || this.readyState == 'loaded'
     || this.readyState == 'complete') ) {
  done=true;
  success();
  script.onload = script.onreadystatechange = null;
  head.removeChild(script);
   }
 };
 head.appendChild(script);
  }
  getScript('http://code.jquery.com/jquery-latest.min.js',function() {
 if (typeof jQuery=='undefined') {
   msg='Sorry, but jQuery wasn\'t able to load';
 } else {
   msg='This page is now jQuerified with v' + jQuery.fn.jquery;
   if (otherlib) {msg+=' and noConflict(). Use $jq(), not $().';}
 }
 return showMsg();
  });
  function showMsg() {
 el.innerHTML=msg;
 b.appendChild(el);
 window.setTimeout(function() {
   if (typeof jQuery=='undefined') {
  b.removeChild(el);
   } else {
  jQuery(el).fadeOut('slow',function() {
    jQuery(this).remove();
  });
  if (otherlib) {
    $jq=jQuery.noConflict();
  }
   }
 } ,2500);
  }
})();

Learn JavaScript!

What to Read to Get Up to Speed in JavaScript.

The best books & blogs for learning JavaScript development. Broken down by experience levels!


My BIG LIST of JavaScript, CSS & HTML Development Tools, Libraries, Projects, and Books.

Constantly updated with the latest and greatest tools. Check it out!

Contact Me

GMail: reybango at gmail dot com
Twitter: @reybango

Haters gonna hate: What's that you said, Cobra?






JavaScript JS Documentation: JS Function Example: Specifying arguments with the Function constructor, JavaScript Function Example: Specifying arguments with the Function constructor

Twitter

Rey Bango is Stephen Fry proof thanks to caching by WP Super Cache