Jquery and Javascript Coding - Examples and Best Practices
Jquery and Javascript Coding - Examples and Best Practices
Jquery and Javascript Coding - Examples and Best Practices
Page 1 of 13
When used correctly, jQuery (http://jquery.com/) 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. [By the way: The network tab (http://www.smashingmagazine.com/network-posts/) (on the top of the page) is updated several times a day. It features selected articles from the best web design blogs!]
1. Why jQuery?
jQuery (http://jquery.com/) 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. 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 scriptingbasically, 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.
http://www.smashingmagazine.com/2008/09/16/jquery-examples-and-best-practices/
18/06/2010
jQuery and JavaScript Coding: Examples and Best Practices - Smashing Magazine
Page 2 of 13
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.
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: 1 ... 2 3 $('a.doSomething').click(function(){ 4 5 // Do something here! alert('You did something, woo hoo!');
http://www.smashingmagazine.com/2008/09/16/jquery-examples-and-best-practices/
18/06/2010
jQuery and JavaScript Coding: Examples and Best Practices - Smashing Magazine
Page 3 of 13
6 }); 7 ... The .click() method in jQuery (http://docs.jquery.com/Events/click) 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. Its fine to use Javascript to enhance the information, make it prettier, or more interactivebut never assume the users 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 its 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 (#Selectors) ) like the one in the following Javascript snippet: 1 var now = new Date(); 2 if(now.getHours() >= 12)
http://www.smashingmagazine.com/2008/09/16/jquery-examples-and-best-practices/
18/06/2010
jQuery and JavaScript Coding: Examples and Best Practices - Smashing Magazine
Page 4 of 13
3{ 4 5 6} 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 isnt run, the page is still 100% semantically pure (X)HTMLno 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 pages 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 jQueryenhanced 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>
http://www.smashingmagazine.com/2008/09/16/jquery-examples-and-best-practices/
18/06/2010
jQuery and JavaScript Coding: Examples and Best Practices - Smashing Magazine
Page 5 of 13
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 selectormore on this later (#Selectors) .
1 $(document); // Activate jQuery for object 2 $('#mydiv') // Element with ID "mydiv" 3 $('p.first') // P tags with class first. 4 $('p[title="Hello"]') // P tags with title "Hello" 5 $('p[title^="H"]') // P tags title starting with H
So, as the Javascript comments suggest:
1. $(document); The first option will apply the jQuery library methods to a DOM object (in this case, the document object). 2. $(#mydiv) The second option will select every <div> that has the <id> attribute set to mydiv. 3. $(p.first) The third option will select all of the <p> tags with the class of first.
http://www.smashingmagazine.com/2008/09/16/jquery-examples-and-best-practices/
18/06/2010
jQuery and JavaScript Coding: Examples and Best Practices - Smashing Magazine
Page 6 of 13
4. $(p[title="Hello"]) This option will select from the page all <p> tags that have a title of Hello. Techniques like this enable the use of much more semantically correct (X)HTML markup, while still facilitating the DOM scripting required to create complex interactions. 5. $(p[title^="H"]) This enables the selection of all of the <p> tags on the page that have a title that starts with the letter H.
These examples barely scratch the surface.
Almost anything you can do in CSS3 will work in jQuery, plus many more complicated selectors. The complete list of selectors is well documented on the jQuery Selectors documentation page (http://docs.jquery.com/Selectors) . If youre feeling super-geeky, you could also read the CSS3 selector specification (http://www.w3.org/TR/css3-selectors/) from the W3C (http://www.w3.org) . Get ready. $(document).ready() Traditionally Javascript events were attached to a document using an onload attribute in the <body> tag of the page. Forget this practice. Wipe it from your mind. jQuery provides us with a special utility on the document object, called ready, allowing us to execute code ONLY after the DOM has completely finished loading. This is the key to unobtrusive DOM scripting, as it allows us to completely separate our Javascript code from our markup. Using $(document).ready(), we can queue up a series of events and have them execute after the DOM is initialized. This means that we can create entire effects for our pages without changing the markup for the elements in question.
Hello World! Why $(document).ready() is SO cool
To demonstrate the beauty of this functionality, lets recreate the standard introduction to Javascript: a Hello World alert box. The following markup shows how we might have run a Hello World alert without jQuery:
Bad markup:
Good markup:
Using this functionality in jQuery is simple. The following code snippet demonstrates how we might call the age-old Hello World alert box after our document has loaded. The true beauty of this markup is that it lives in an external Javascript file. There is NO impact on the (X)HTML page.
http://www.smashingmagazine.com/2008/09/16/jquery-examples-and-best-practices/
18/06/2010
jQuery and JavaScript Coding: Examples and Best Practices - Smashing Magazine
Page 7 of 13
1 $(document).ready(function() 2{ 3 4 });
How it works
alert('Hello World');
The $(document).ready() function takes a function as its argument. (In this case, an anonymous function is created inlinea technique that is used throughout the jQuery documentation.) The function passed to $(document).ready() is called after the DOM has finished loading and executes the code inside the function, in this case, calling the alert. Dynamic CSS Rule Creation One problem with many DOM scripting effects is that they often require us to hide elements of the document from view. This hiding is usually achieved through CSS. However, this is less than desirable. If a users browser does not support Javascript (or has Javascript disabled), yet does support CSS, then the elements that we hide in CSS will never be visible, since our Javascript interactions will not have run. The solution to this comes in the form of a plugin for jQuery called cssRule (http://plugins.jquery.com/project/jquerycssrule) , which allows us to use Javascript to easily add CSS rules to the style sheet of the document. This means we can hide elements of the page using CSShowever the CSS is ONLY executed IF Javascript is running.
Bad markup:
HTML: <h2>This is a heading</h2> <p class="hide-me-first"> This is some information about the heading. </p> CSS: p.hide-me-first { display: none; }
Assuming that a paragraph with the class of hide-me-first is going to first be hidden by CSS and then be displayed by a Javascript after some future user interaction, if the Javascript never runs the content will never be visible.
Good markup:
HTML: <h2>This is a heading</h2> <p class="hide-me-first"> This is some information about the heading. </p>
http://www.smashingmagazine.com/2008/09/16/jquery-examples-and-best-practices/
18/06/2010
jQuery and JavaScript Coding: Examples and Best Practices - Smashing Magazine
Page 8 of 13
Using a $(document).ready() Javascript here to hide the paragraph element means that if Javascript is disabled, the paragraphs wont ever be hiddenso the content is still accessible. This is the key reason for runtime, Javascript-based, dynamic CSS rule creation.
4. Conclusion
jQuery is an extremely powerful library that provides all the tools necessary to create beautiful interactions and animations in web pages, while empowering the developer to do so in an accessible and degradable manner. This article has covered: 1. 2. 3. 4. Why unobtrusive DOM scripting is so important for accessibility, Why jQuery is the natural choice to implement unobtrusive DOM scripting effects, How jQuery selectors work, How to implement unobtrusive CSS rules in jQuery.
5. Further Reading
Further Reading: jQuery and JavaScript Practices 1. jQuery Web Site: How jQuery Works (http://docs.jquery.com/How_jQuery_Works) and Tutorials (http://docs.jquery.com/Tutorials) John Resig + Other Contributors One of jQuerys true strengths is the documentation provided by John Resig and his team. 2. 51 Best jQuery Tutorials and Examples (http://www.noupe.com/tutorial/51-best-of-jquery -tutorials-and-examples.html) 3. Easy As Pie: Unobtrusive JavaScript (http://www.phazm.com/notes/javascript/easy-as-pie -unobtrusive-javascript/) 4. Seven Rules of Unobtrusive JavaScript (http://icant.co.uk/articles/seven-rules-ofunobtrusive-javascript/) 5. Learning jQuery (http://www.learningjquery.com/) 6. Visual jQuery (http://www.visualjquery.com/) 7. jQuery Tutorials For Designers (http://www.webdesignerwall.com/tutorials/jquerytutorials-for-designers/) 8. jQuery For Designers (http://jqueryfordesigners.com/) jQuery for Designers: learn how easy it is to apply web interaction using jQuery. 9. 15 Days Of jQuery (http://15daysofjquery.com/) jQuery tutorials and example code that takes you from zero to hero in no time flat. 10. 15 Resources To Get You Started With jQuery From Scratch (http://nettuts.com/javascript-ajax/15-resources-to-get-you-started-with-jquery-fromscratch/) 11. The Seven Rules Of Pragmatic Progressive Enhancement (http://ajaxian.com/archives/the-seven-rules-of-pragmatic-progressive-enhancement) 12. The Behaviour Layer Slides (http://adactio.com/atmedia2005/) Jeremy Keith Great slide notes giving a quick rundown on unobtrusive Javascripting.
http://www.smashingmagazine.com/2008/09/16/jquery-examples-and-best-practices/
18/06/2010
jQuery and JavaScript Coding: Examples and Best Practices - Smashing Magazine
Page 9 of 13
13. A List Apart: Behavioral Separation (http://www.alistapart.com/articles/behavioralseparation) Jeremy Keith A more in-depth explanation of the idea of separating Javascript into an unobtrusive behavioural layer. 14. Unobtrusive JavaScript with jQuery (http://simonwillison.net/static/2008/xtech/) Simon Willison A great set of slides about using jQuery unobtrusively. Also, finishes with a wonderful summary of jQuery methods and usage. Further Reading: Semantic Markup 1. Wikipedia: Definition of Semantics (http://en.wikipedia.org/wiki/Semantic) Its worth understanding the idea of semantics in general prior to trying to wrap ones head around the concept of semantic markup. 2. Who cares about semantic markup? (http://www.mezzoblue.com/archives/2005/05/30/who_cares_ab/) Dave Shea Dave Shea explores the benefits of semantic markup and 3. Standards dont necessarily have anything to do with being semantically correct (http://www.kottke.org/03/08/standards-semantically-correct) Jason Kottke Kottke discusses the differences between standards compliance and semantic markup. 4. CSS3 selector specification (http://www.w3.org/TR/css3-selectors/) W3C The complete specification for CSS3 selectors (most of which work perfectly in jQuery selectors also). This is great reading for anyone who likes to keep up to date with best practices and standards compliance.
Alex Holt (http://www.smashingmagazine.com/author/alex-holt/) 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 Spain. His blog can be found at: soyrex.com (http://soyrex.com) , where he writes sporadically about a wide range of design and development topics (as well as the occasional off-topic rant). 11 Bookmark (http://delicious.com/post? url=http://www.smashingmagazine.com/2008/09/16/jquery-examples-and-bestpractices/&title=jQuery and JavaScript Coding: Examples and Best Practices) Vote up (http://www.stumbleupon.com/submit? url=http://www.smashingmagazine.com/2008/09/16/jquery-examples-and-bestpractices/&title=jQuery and JavaScript Coding: Examples and Best Practices) Retweet (http://twitter.com/home?status=Reading 'jQuery and JavaScript Coding: Examples and Best Practices' (via @smashingmag) http://tinyurl.com/6bm5s9 ) Share (http://www.facebook.com/sharer.php? u=http://www.smashingmagazine.com/2008/09/16/jquery-examples-and-bestpractices/&t=jQuery and JavaScript Coding: Examples and Best Practices) 1
http://www.smashingmagazine.com/2008/09/16/jquery-examples-and-best-practices/
18/06/2010
jQuery and JavaScript Coding: Examples and Best Practices - Smashing Magazine
Page 10 of 13
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
http://www.smashingmagazine.com/2008/09/16/jquery-examples-and-best-practices/
18/06/2010
jQuery and JavaScript Coding: Examples and Best Practices - Smashing Magazine
Page 11 of 13
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
http://www.smashingmagazine.com/2008/09/16/jquery-examples-and-best-practices/
18/06/2010
jQuery and JavaScript Coding: Examples and Best Practices - Smashing Magazine
Page 12 of 13
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
http://www.smashingmagazine.com/2008/09/16/jquery-examples-and-best-practices/
18/06/2010
jQuery and JavaScript Coding: Examples and Best Practices - Smashing Magazine
Page 13 of 13
167 168 169 170 171 172 Smashing Media GmbH. Created by Sven Lennartz & Vitaly Friedman (/about)
http://www.smashingmagazine.com/2008/09/16/jquery-examples-and-best-practices/
18/06/2010