jQuery and Javascript Coding_ Examples and Best Practices

download jQuery and Javascript Coding_ Examples and Best Practices

of 13

Transcript of jQuery and Javascript Coding_ Examples and Best Practices

  • 8/2/2019 jQuery and Javascript Coding_ Examples and Best Practices

    1/13

    jQuery and JavaScript Coding: Examples and Best Practices

    By Alex Holt (http://www.smashingmagazine.com/author/alex-holt/)

    September 16th, 2008Coding (http://www.smashingmagazine.com/category/coding/)172 Comments (http://www.smashingmagazine.com/2008/09/16/jquery-examples-and-best-

    practices/#comments)

    When used correctly,jQuery (http://jquery.com/) canhelp you make your website more interactive, interestingand exciting. This article will share some best practicesand examples for using the popular Javascript frameworkto create unobtrusive, accessible DOM scripting effects.The article will explore what constitutes best practices

    with regard to Javascript and, furthermore, why jQueryis a good choice of a framework to implement bestpractices.

    [By the way: The network tab(http://www.smashingmagazine.com/network-posts/) (onthe top of the page) is updated several times a day. It features selected articles from the best webdesign 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 thepossibilities are (almost) infinite.

    Javascript and Best Practices

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

    The answer to this question is still unresolved, however, the emergence of Javascript frameworkslike 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 thumbhere 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) toaccess the Document Object Model, it has widely become accepted as a way of describing whatshould really be called unobtrusive DOM scriptingbasically, the art of adding Javascript toyour 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.

    Page 1 of 13Query and JavaScript Coding: Examples and Best Practices - Smashing Magazine

    18/06/2010http://www.smashingmagazine.com/2008/09/16/jquery-examples-and-best-practices/

  • 8/2/2019 jQuery and Javascript Coding_ Examples and Best Practices

    2/13

    The Bottom Line: Accessible, Degradable Content

    The aim of any web producer, designer or developer is to create content that is accessible to thewidest range of audience. However, this has to be carefully balanced with design, interactivity andbeauty. Using the theories set out in this article, designers, developers and web producers willhave 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.0animated sliding news ticker widget in a web page, while still ensuring that it fails gracefully if avisitors browser cant (or wont) 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 andindependent of (X)HTML and CSS. (X)HTML is the markup, CSS the presentation and Javascriptthe behavioural layer. This means storing ALL Javascript code in external script files and buildingpages 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 wipedfrom your mind.

    Click!

    Good markup:

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

    Click!

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

    1 ...

    2

    3 $('a.doSomething').click(function(){

    4 // Do something here!

    5 alert('You did something, woo hoo!');

    Page 2 of 13Query and JavaScript Coding: Examples and Best Practices - Smashing Magazine

    18/06/2010http://www.smashingmagazine.com/2008/09/16/jquery-examples-and-best-practices/

  • 8/2/2019 jQuery and Javascript Coding_ Examples and Best Practices

    3/13

    6 });

    7 ...

    The .click() method in jQuery (http://docs.jquery.com/Events/click) allows us to easily attach aclick event to the result(s) of our selector. So the code will select all of the tags of classdoSomething 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 inlineJavascript code.

    Rule #2: NEVER Depend on Javascript

    To be truly unobtrusive, a developer should never rely on Javascript support to deliver content orinformation. Its fine to use Javascript to enhance the information, make it prettier, or moreinteractivebut never assume the users browser will have Javascript enabled. This rule of thumbcan in fact be applied to any third-party technology, such as Flash or Java. If its not built intoevery 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 (orafternoon) message on a site, depending on the time of day. (Obviously this is a rudimentaryexample and would in fact probably be achieved in some server-side scripting language).

    var now = new Date();

    if(now.getHours() < 12)

    document.write('Good Morning!');

    else

    document.write('Good Afternoon!');

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

    Good markup:

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

    Good Morning!

    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 followingJavascript snippet:

    1 varnow = newDate();

    2 if(now.getHours() >= 12)

    Page 3 of 13Query and JavaScript Coding: Examples and Best Practices - Smashing Magazine

    18/06/2010http://www.smashingmagazine.com/2008/09/16/jquery-examples-and-best-practices/

  • 8/2/2019 jQuery and Javascript Coding_ Examples and Best Practices

    4/13

    3 {

    4 vargoodDay = $('p[title="Good Day Message"]');

    5 goodDay.text('Good Afternoon!');

    6 }

    The beauty here is that all the Javascript lives in an external script file and the page is rendered asstandard (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 theafternoon, the page would still say Good morning. However, this can be seen as an acceptabledegradation.

    Rule #3: Semantic and Accessible Markup Comes First

    It is very important that the (X)HTML markup is semantically structured. (While it is outside thescope 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 ruleof thumb to get one started.

    Semantic markup is important to unobtrusive DOM scripting because it shapes the path thedeveloper 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 correctmarkup (leaving an (X)HTML document that is clean and readable, and separating the behaviourallayer).

    Terrible markup:

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

    First Option

    First option description

    Second OptionSecond option description

    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.

    First Option

    First option description

    Second Option

    Page 4 of 13Query and JavaScript Coding: Examples and Best Practices - Smashing Magazine

    18/06/2010http://www.smashingmagazine.com/2008/09/16/jquery-examples-and-best-practices/

  • 8/2/2019 jQuery and Javascript Coding_ Examples and Best Practices

    5/13

    Second option description

    Good markup:

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

    First Option

    First option description

    Second Option

    Second option description

    The of OptionList will enable us to target this particular definition list in jQuery using a

    selectormore on this later (#Selectors) .

    3. Understanding jQuery for Unobtrusive DOM Scripting

    This section will explore three priceless tips and tricks for using jQuery to implement bestpractices 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 insome way.

    If youre familiar with CSS then youll understand selectors in jQuery; theyre almost the samething 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:

    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:

    $(document);The first option will apply the jQuery library methods to a DOM object (in this case, thedocument object).

    1.

    $(#mydiv)The second option will select every that has the attribute set to mydiv.2.

    $(p.first)The third option will select all of the

    tags with the class of first.

    3.

    Page 5 of 13Query and JavaScript Coding: Examples and Best Practices - Smashing Magazine

    18/06/2010http://www.smashingmagazine.com/2008/09/16/jquery-examples-and-best-practices/

  • 8/2/2019 jQuery and Javascript Coding_ Examples and Best Practices

    6/13

    $(p[title="Hello"])This option will select from the page all

    tags that have a title of Hello. Techniqueslike this enable the use of much more semantically correct (X)HTML markup, while stillfacilitating the DOM scripting required to create complex interactions.

    4.

    $(p[title^="H"])This enables the selection of all of the

    tags on the page that have a title that starts withthe letter H.

    5.

    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 thejQuery Selectors documentation page(http://docs.jquery.com/Selectors) . If youre feeling super-geeky, you could also read the CSS3selector 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 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 toexecute code ONLY after the DOM has completely finished loading. This is the key tounobtrusive DOM scripting, as it allows us to completely separate our Javascript code from ourmarkup. Using $(document).ready(), we can queue up a series of events and have themexecute after the DOM is initialized.

    This means that we can create entire effects for our pages without changing the markup for theelements in question.

    Hello World! Why $(document).ready() is SO cool

    To demonstrate the beauty of this functionality, lets recreate the standard introduction toJavascript: a Hello World alert box.

    The following markup shows how we might have run a Hello World alert without jQuery:

    Bad markup:

    alert('Hello World');

    Good markup:

    Using this functionality in jQuery is simple. The following code snippet demonstrates how wemight call the age-old Hello World alert box after our document has loaded. The true beauty ofthis markup is that it lives in an external Javascript file. There is NO impact on the (X)HTMLpage.

    Page 6 of 13Query and JavaScript Coding: Examples and Best Practices - Smashing Magazine

    18/06/2010http://www.smashingmagazine.com/2008/09/16/jquery-examples-and-best-practices/

  • 8/2/2019 jQuery and Javascript Coding_ Examples and Best Practices

    7/13

    1 $(document).ready(function()

    2 {

    3 alert('Hello World');

    4 });

    How it works

    The $(document).ready() function takes a function as its argument. (In this case, an anonymousfunction is created inlinea technique that is used throughout the jQuery documentation.) Thefunction passed to $(document).ready() is called after the DOM has finished loading and executesthe 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 thandesirable. If a users browser does not support Javascript (or has Javascript disabled), yet doessupport CSS, then the elements that we hide in CSS will never be visible, since our Javascriptinteractions 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 addCSS rules to the style sheet of the document. This means we can hide elements of the page usingCSShowever the CSS is ONLY executed IF Javascript is running.

    Bad markup:

    HTML:

    This is a heading

    This is some information about the heading.

    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 andthen be displayed by a Javascript after some future user interaction, if the Javascript never runs thecontent will never be visible.

    Good markup:

    HTML:

    This is a heading

    This is some information about the heading.

    Page 7 of 13Query and JavaScript Coding: Examples and Best Practices - Smashing Magazine

    18/06/2010http://www.smashingmagazine.com/2008/09/16/jquery-examples-and-best-practices/

  • 8/2/2019 jQuery and Javascript Coding_ Examples and Best Practices

    8/13

    jQuery Javascript:

    $(document).ready(function{

    jQuery.cssRule("p.hide-me-first", "display", "none");

    });

    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. Thisis 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 beautifulinteractions and animations in web pages, while empowering the developer to do so in anaccessible and degradable manner.

    This article has covered:

    Why unobtrusive DOM scripting is so important for accessibility,1.Why jQuery is the natural choice to implement unobtrusive DOM scripting effects,2.How jQuery selectors work,3.How to implement unobtrusive CSS rules in jQuery.4.

    5. Further Reading

    Further Reading: jQuery and JavaScript Practices

    jQuery Web Site:How jQuery Works (http://docs.jquery.com/How_jQuery_Works)andTutorials (http://docs.jquery.com/Tutorials)

    John Resig + Other ContributorsOne of jQuerys true strengths is the documentation provided by John Resig and his team.

    1.

    51 Best jQuery Tutorials and Examples (http://www.noupe.com/tutorial/51-best-of-jquery-tutorials-and-examples.html)

    2.

    Easy As Pie: Unobtrusive JavaScript (http://www.phazm.com/notes/javascript/easy-as-pie-unobtrusive-javascript/)

    3.

    Seven Rules of Unobtrusive JavaScript (http://icant.co.uk/articles/seven-rules-of-unobtrusive-javascript/)

    4.

    Learning jQuery (http://www.learningjquery.com/)5.Visual jQuery (http://www.visualjquery.com/)6.

    jQuery Tutorials For Designers (http://www.webdesignerwall.com/tutorials/jquery-

    tutorials-for-designers/)

    7.

    jQuery For Designers (http://jqueryfordesigners.com/)jQuery for Designers: learn how easy it is to apply web interaction using jQuery.

    8.

    15 Days Of jQuery (http://15daysofjquery.com/)jQuery tutorials and example code that takes you from zero to hero in no time flat.

    9.

    15 Resources To Get You Started With jQuery From Scratch(http://nettuts.com/javascript-ajax/15-resources-to-get-you-started-with-jquery-from-scratch/)

    10.

    The Seven Rules Of Pragmatic Progressive Enhancement(http://ajaxian.com/archives/the-seven-rules-of-pragmatic-progressive-enhancement)

    11.

    The Behaviour Layer Slides (http://adactio.com/atmedia2005/)

    Jeremy KeithGreat slide notes giving a quick rundown on unobtrusive Javascripting.

    12.

    Page 8 of 13Query and JavaScript Coding: Examples and Best Practices - Smashing Magazine

    18/06/2010http://www.smashingmagazine.com/2008/09/16/jquery-examples-and-best-practices/

  • 8/2/2019 jQuery and Javascript Coding_ Examples and Best Practices

    9/13

    A List Apart: Behavioral Separation(http://www.alistapart.com/articles/behavioralseparation) Jeremy KeithA more in-depth explanation of the idea of separating Javascript into an unobtrusivebehavioural layer.

    13.

    Unobtrusive JavaScript with jQuery (http://simonwillison.net/static/2008/xtech/)Simon WillisonA great set of slides about using jQuery unobtrusively. Also, finishes with a wonderfulsummary of jQuery methods and usage.

    14.

    Further Reading: Semantic Markup

    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 headaround the concept of semantic markup.

    1.

    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

    2.

    Standards dont necessarily have anything to do with being semantically correct(http://www.kottke.org/03/08/standards-semantically-correct)

    Jason KottkeKottke discusses the differences between standards compliance and semantic markup.

    3.

    CSS3 selector specification (http://www.w3.org/TR/css3-selectors/)W3CThe complete specification for CSS3 selectors (most of which work perfectly in jQueryselectors also). This is great reading for anyone who likes to keep up to date with bestpractices and standards compliance.

    4.

    Alex Holt (http://www.smashingmagazine.com/author/alex-holt/)

    Alex Holt is a professional interactive designer and web developer who has worked successfullyfor 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 anddevelopment 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-best-

    practices/&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-best-

    practices/&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-best-

    practices/&t=jQuery and JavaScript Coding: Examples and Best Practices)

    1

    Page 9 of 13Query and JavaScript Coding: Examples and Best Practices - Smashing Magazine

    18/06/2010http://www.smashingmagazine.com/2008/09/16/jquery-examples-and-best-practices/

  • 8/2/2019 jQuery and Javascript Coding_ Examples and Best Practices

    10/13

    2345678910111213141516171819

    2021222324252627282930

    3132333435363738394041

    4243444546474849505152

    53545556

    Page 10 of 13Query and JavaScript Coding: Examples and Best Practices - Smashing Magazine

    18/06/2010http://www.smashingmagazine.com/2008/09/16/jquery-examples-and-best-practices/

  • 8/2/2019 jQuery and Javascript Coding_ Examples and Best Practices

    11/13

    575859606162636465666768697071727374

    7576777879808182838485

    8687888990919293949596

    979899100101102103104105106107

    108109110111

    Page 11 of 13Query and JavaScript Coding: Examples and Best Practices - Smashing Magazine

    18/06/2010http://www.smashingmagazine.com/2008/09/16/jquery-examples-and-best-practices/

  • 8/2/2019 jQuery and Javascript Coding_ Examples and Best Practices

    12/13

    112113114115116117118119120121122123124125126127128129

    130131132133134135136137138139140

    141142143144145146147148149150151

    152153154155156157158159160161162

    163164165166

    Page 12 of 13Query and JavaScript Coding: Examples and Best Practices - Smashing Magazine

    18/06/2010http://www.smashingmagazine.com/2008/09/16/jquery-examples-and-best-practices/

  • 8/2/2019 jQuery and Javascript Coding_ Examples and Best Practices

    13/13

    167168

    169170171172

    Smashing Media GmbH. Created by Sven Lennartz & Vitaly Friedman (/about)

    Page 13 of 13Query and JavaScript Coding: Examples and Best Practices - Smashing Magazine