About The Author Alex Holt is a professional interactive designer and web developer who has worked successfully for a variety of clients in Australia, UK, USA and most recently … More about Alex…

jQuery and JavaScript Coding: Examples and Best Practices

Smashing Newsletter Upgrade your inbox and get our editors’ picks twice a month. Your email Subscribe →

When used correctly,jQuery can help you make your website more interactive, interesting and exciting. This article will share some best practices and examples for using the popular Javascript framework to create unobtrusive, accessible DOM scripting effects.

When used correctly, jQuery can help you make your website more interactive, interesting and exciting. This article will share some best practices and examples for using the popular Javascript framework to create unobtrusive, accessible DOM scripting effects. The article will explore what constitutes best practices with regard to Javascript and, furthermore, why jQuery is a good choice of a framework to implement best practices.

You may want to take a look at the following newer posts:

1. Why jQuery?

jQuery is ideal because it can create impressive animations and interactions. jQuery is simple to understand and easy to use, which means the learning curve is small, while the possibilities are (almost) infinite.

Meet Smashing Book 6 — our brand new book focused on real challenges and real front-end solutions in the real world: from design systems and accessible single-page apps to CSS Custom Properties, CSS Grid, Service Workers, performance, AR/VR and responsive art direction. With Marcy Sutton, Yoav Weiss, Lyza D. Gardner, Laura Elizabeth and many others. Table of Contents →

Javascript and Best Practices

Javascript has long been the subject of many heated debates about whether it is possible to use it while still adhering to best practices regarding accessibility and standards compliance.

The answer to this question is still unresolved, however, the emergence of Javascript frameworks like jQuery has provided the necessary tools to create beautiful websites without having to worry (as much) about accessibility issues.

Obviously there are cases where a Javascript solution is not the best option. The rule of thumb here is: use DOM scripting to enhance functionality, not create it.

Unobtrusive DOM Scripting

While the term “DOM scripting” really just refers to the use of scripts (in this case, Javascripts) to access the Document Object Model, it has widely become accepted as a way of describing what should really be called “unobtrusive DOM scripting”—basically, the art of adding Javascript to your page in such a way that if there were NO Javascript, the page would still work (or at least degrade gracefully). In the website world, our DOM scripting is done using Javascript.

The Bottom Line: Accessible, Degradable Content

The aim of any web producer, designer or developer is to create content that is accessible to the widest range of audience. However, this has to be carefully balanced with design, interactivity and beauty. Using the theories set out in this article, designers, developers and web producers will have the knowledge and understanding to use jQuery for DOM scripting in an accessible and degradable way; maintaining content that is beautiful, functional AND accessible.

2. Unobtrusive DOM Scripting?

In an ideal world, websites would have dynamic functionality AND effects that degrade well. What does this mean? It would mean finding a way to include, say, a snazzy Javascript Web 2.0 animated sliding news ticker widget in a web page, while still ensuring that it fails gracefully if a visitor’s browser can’t (or won’t) run Javascripts.

The theory behind this technique is quite simple: the ultimate aim is to use Javascript for non-invasive, “behavioural” elements of the page. Javascript is used to add or enhance interactivity and effects. The primary rules for DOM scripting follow.

Rule #1: Separate Javascript Functionality

Separate Javascript functionality into a “behavioural layer,” so that it is separate from and independent of (X)HTML and CSS. (X)HTML is the markup, CSS the presentation and Javascript the behavioural layer. This means storing ALL Javascript code in external script files and building pages that do not rely on Javascript to be usable.

For a demonstration, check out the following code snippets:

Bad markup:

Never include Javascript events as inline attributes. This practice should be completely wiped from your mind.

<a onclick="doSomething()" href="#">Click!</a>

Good markup:

All Javascript behaviours should be included in external script files and linked to the document with a <script> tag in the head of the page. So, the anchor tag would appear like this:

<a href="backuplink.html" class="doSomething">Click!</a>

And the Javascript inside the myscript.js file would contain something like this:

... $('a.doSomething').click(function(){ // Do something here! alert('You did something, woo hoo!'); }); ...

The .click() method in jQuery allows us to easily attach a click event to the result(s) of our selector. So the code will select all of the <a> tags of class “doSomething” and attach a click event that will call the function. In practice, this

In Rule #2 there is a further demonstration of how a similar end can be achieved without inline Javascript code.

Rule #2: NEVER Depend on Javascript

To be truly unobtrusive, a developer should never rely on Javascript support to deliver content or information. It’s fine to use Javascript to enhance the information, make it prettier, or more interactive—but never assume the user’s browser will have Javascript enabled. This rule of thumb can in fact be applied to any third-party technology, such as Flash or Java. If it’s not built into every web browser (and always enabled), then be sure that the page is still completely accessible and usable without it.

Bad markup:

The following snippet shows Javascript that might be used to display a “Good morning” (or “afternoon”) message on a site, depending on the time of day. (Obviously this is a rudimentary example and would in fact probably be achieved in some server-side scripting language).

<script language="javascript"> var now = new Date(); if(now.getHours() < 12) document.write('Good Morning!'); else document.write('Good Afternoon!'); </script>

This inline script is bad because if the target browser has Javascript disabled, NOTHING will be rendered, leaving a gap in the page. This is NOT graceful degradation. The non-Javascript user is missing out on our welcome message.

Good markup:

A semantically correct and accessible way to implement this would require much simpler and more readable (X)HTML, like:

<p title="Good Day Message">Good Morning!</p>

By including the “title” attribute, this paragraph can be selected in jQuery using a selector (selectors are explained later in this article) like the one in the following Javascript snippet:

var now = new Date(); if(now.getHours() >= 12) { var goodDay = $('p[title="Good Day Message"]'); goodDay.text('Good Afternoon!'); }

The beauty here is that all the Javascript lives in an external script file and the page is rendered as standard (X)HTML, which means that if the Javascript isn’t run, the page is still 100% semantically pure (X)HTML—no Javascript cruft. The only problem would be that in the afternoon, the page would still say “Good morning.” However, this can be seen as an acceptable degradation.

Rule #3: Semantic and Accessible Markup Comes First

It is very important that the (X)HTML markup is semantically structured. (While it is outside the scope of this article to explain why, see the links below for further reading on semantic markup.) The general rule here is that if the page’s markup is semantically structured, it should follow that it is also accessible to a wide range of devices. This is not always true, though, but it is a good rule of thumb to get one started.

Semantic markup is important to unobtrusive DOM scripting because it shapes the path the developer will take to create the DOM scripted effect. The FIRST step in building any jQuery-enhanced widget into a page is to write the markup and make sure that the markup is semantic. Once this is achieved, the developer can then use jQuery to interact with the semantically correct markup (leaving an (X)HTML document that is clean and readable, and separating the behavioural layer).

Terrible markup:

The following snippet shows a typical list of items and descriptions in a typical (and terribly UNsemantic) way.

<table> <tr> <td onclick="doSomething();">First Option</td> <td>First option description</td> </tr> <tr> <td onclick="doSomething();">Second Option</td> <td>Second option description</td> </tr> </table>

Bad markup:

The following snippet shows a typical list of items and descriptions in a more semantic way. However, the inline Javascript is far from perfect.

<dl> <dt onclick="doSomething();">First Option</dt> <dd>First option description</dd> <dt onclick="doSomething();">Second Option</dt> <dd>Second option description</dd> </dl>

Good markup:

This snippet shows how the above list should be marked up. Any interaction with Javascript would be attached at DOM load using jQuery, effectively removing all behavioural markup from the rendered (X)HTML.

<dl id="OptionList"> <dt>First Option</dt> <dd>First option description</dd> <dt>Second Option</dt> <dd>Second option description</dd> </dl>

The <id> of “OptionList” will enable us to target this particular definition list in jQuery using a selector—more on this later.

3. Understanding jQuery for Unobtrusive DOM Scripting

This section will explore three priceless tips and tricks for using jQuery to implement best practices and accessible effects.

Understanding Selectors: the Backbone of jQuery

The first step to unobtrusive DOM scripting (at least in jQuery and Prototype) is using selectors. Selectors can (amazingly) select an element out of the DOM tree so that it can be manipulated in some way.

If you’re familiar with CSS then you’ll understand selectors in jQuery; they’re almost the same thing and use almost the same syntax. jQuery provides a special utility function to select elements. It is called $.

A set of very simple examples of jQuery selectors:

$(document); // Activate jQuery for object $('#mydiv') // Element with ID "mydiv" $('p.first') // P tags with class first. $('p[title="Hello"]') // P tags with title "Hello" $('p[title^="H"]') // P tags title starting with H