Progressive Enhancement with jQuery

While I work on finishing up an overdue post on the amazing An Event Apart San Francisco conference I attended last week, I thought I would at least write about one of the many new concepts that was discussed.

Progressive Enhancement (PE) is the concept of adding functionality or enhancements to the presentation and behavior of a webpage, using modern technologies such as CSS and Javascript. The PE approach adds the additional features thru externally linked files in order to avoid forcing older/less capable browsers to process data they don’t understand or can’t handle. In other words, the strategy demands that the basic content always be available, then add the fancier layout and features for browsers that can show it.

I’m going to show a quick but usable example of PE using jQuery. In this example, I am going to show how you can dynamically add an “external link” icon – to links inside a specific area of your webpage.

1. download the current release of jQuery (at this writing – 1.2.6) and add it to your webpage in the tag.

2. Next, we will utilize the jQuery approach of executing Javascript code when the Document is loaded and the DOM is ready to be manipulated.

$(document).ready(function() { });

3. Now, if we want to add an image after each external link, we can use the jQuery filter function which will addall elements that match a specified expression.

In the section above, we'll add:

$("a").filter(".selected")

4. The expression will be another function that tests the hostname property of the link to see if it is different that the current page’s hostname.

Try this:

function() { return this.hostname && this.hostname !== location.hostname; })

5. Lastly, we’ll use jQuery to insert the image after the link that matches the test expression – namely an external link!

.after(' <img src="/images/ext.png" alt="External Link">');

6. Let’s put it all together!

Here’s the sum of the Javascript that we’ve written:

$(document).ready(function() { $('#extlinks a').filter(function() { return this.hostname && this.hostname !== location.hostname; }).after(' <img src="/images/ext.png" alt="External Link">'); });

put that code in a Javascript file and include it after your jQuery code in your page’s :

That’s it! Now go give it a try for yourself.

Leave a Reply

Get Adobe Flash player
%d bloggers like this: