Menu Search
Jump to the content X X
Smashing Conf Barcelona

You know, we use ad-blockers as well. We gotta keep those servers running though. Did you know that we publish useful books and run friendly conferences — crafted for pros like yourself? E.g. our upcoming SmashingConf Barcelona, dedicated to smart front-end techniques and design patterns.

jQuery and JavaScript Coding: Examples and Best Practices

Things to do today..

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. [Content Care Nov/15/2016]

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

1. Why jQuery? Link

jQuery5 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 Link

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 Link

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 Link

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? Link

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 Link

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:

CrossBad markup: Link

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

<a onclick="doSomething()" href="#">Click!</a>
TickGood markup: Link

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:


	// Do something here!
	alert('You did something, woo hoo!');

The .click() method in jQuery6 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 Link

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.

CrossBad markup: Link

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!');
	document.write('Good Afternoon!');

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.

TickGood markup: Link

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 article7) 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 Link

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).

CrossTerrible markup: Link

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

        <td onclick="doSomething();">First Option</td>
        <td>First option description</td>
        <td onclick="doSomething();">Second Option</td>
        <td>Second option description</td>
CrossBad markup: Link

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

    <dt onclick="doSomething();">First Option</dt>
    <dd>First option description</dd>
    <dt onclick="doSomething();">Second Option</dt>
    <dd>Second option description</dd>
TickGood markup: Link

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>

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

3. Understanding jQuery for Unobtrusive DOM Scripting Link

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 Link

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: Link
$(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
So, as the Javascript comments suggest: Link
  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”.
  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. Link

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 page9. If you’re feeling super-geeky, you could also read the CSS3 selector specification2010 from the W3C.

Get 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 Link

To demonstrate the beauty of this functionality, let’s 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:

CrossBad markup: Link
<script language="javascript">
alert('Hello World');
TickGood markup: Link

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.

	alert('Hello World');
How it works Link

The $(document).ready() function takes a function as its argument. (In this case, an anonymous function is created inline—a 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 Link

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 user’s 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, 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 CSS—however the CSS is ONLY executed IF Javascript is running.

CrossBad markup: Link
<h2>This is a heading</h2>
<p class="hide-me-first">
This is some information about the heading.

	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.

TickGood markup: Link
<h2>This is a heading</h2>
<p class="hide-me-first">
This is some information about the heading.

jQuery Javascript:
	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 won’t ever be hidden—so the content is still accessible. This is the key reason for runtime, Javascript-based, dynamic CSS rule creation.

4. Conclusion Link

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. Why unobtrusive DOM scripting is so important for accessibility,
  2. Why jQuery is the natural choice to implement unobtrusive DOM scripting effects,
  3. How jQuery selectors work,
  4. How to implement unobtrusive CSS rules in jQuery.

5. Further Reading Link

Further Reading: jQuery and JavaScript Practices Link

    1. jQuery Web Site: How jQuery Works11 and Tutorials12
      John Resig + Other Contributors
      One of jQuery’s true strengths is the documentation provided by John Resig and his team.
    2. Learning jQuery13
    3. jQuery Tutorials For Designers14
    4. The Seven Rules Of Pragmatic Progressive Enhancement15
    5. A List Apart: Behavioral Separation
      16Jeremy Keith
      A more in-depth explanation of the idea of separating Javascript into an unobtrusive “behavioural” layer.

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 Link

  1. Wikipedia: Definition of Semantics17
    It’s worth understanding the idea of semantics in general prior to trying to wrap one’s head around the concept of semantic markup.
  2. Who cares about semantic markup?18
    Dave Shea
    Dave Shea explores the benefits of semantic markup and
  3. Standards don’t necessarily have anything to do with being semantically correct19
    Jason Kottke
    Kottke discusses the differences between standards compliance and semantic markup.
  4. CSS3 selector specification2010
    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.

Footnotes Link

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7 #Selectors
  8. 8 #Selectors
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20

↑ Back to top Tweet itShare on Facebook

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:, where he writes sporadically about a wide range of design and development topics (as well as the occasional off-topic rant).

  1. 1

    Great Post as usual.

  2. 2

    yesss I love jquery

  3. 3

    I just started to work with jQuery and this article is really useful for me. Thanks :-)

  4. 4

    nice work!

  5. 5

    Great review of why jQuery is worth using. :)

  6. 6


  7. 7

    Great article!

    (btw what is being used to display the code? )

  8. 8

    Yes, Jquery Is really cool! Useful, Fast and Scalable. We have been using Jquery for over 10 of our projects to deliver best UI to our customers

  9. 9

    quite a good article.

    just to let you know, the code snippets are showing up twice for each one.

  10. 10

    As always, well done. We have moved to almost exclusively using jQuery as our framework of choice. Look forward to more and better ways to use javascript to replace flash where only rudimentary animation is needed and as a tool to build functional apps.

  11. 11

    I don’t mean to be picky, but your <script> tag should read <script type=”text/javascript”>, not <script language=”javascript”>.

    I’m just getting into jQuery though, and this is a great first look. Thanks

  12. 12

    woow very nice article :) thank you

  13. 13

    Good post… but I figure that if you’re going to use jquery or any scripting library, you are probably creating a site for users that have javascript enabled and expect it to be that way.

    If it’s a banking site or something mission critical, probably shouldn’t be using any javascript at all…. but for everything else I think it’s safe to assume users have javascript enabled.

    I’m sure people would disagree :). Nice post though, I like the points about not using inline javascript at all… something I didn’t think about too much.

  14. 14

    Nice article. jQuery is wonderful. It seems strange to me that you mention a few times about never depending on javascript in an article about a javascript dependent package. Yes, it’s important to design your webapp to behave properly in a javascript-less environment but to say to NEVER depend on it a little extreme in this age. There are simply webapps that can not be implemented as markup. Games for example. It’s my opinion that javascript should be considered to be as ubiquitous as html. Otherwise, it’s like expecting to produce a back-office application using Word.

  15. 15

    Whats the diference betwen using:

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

    instead of :


  16. 16

    This post was incredibly well structured.

    Thanks for the informative article.

  17. 17

    I think article is hogwash.. its written by someone who has obviously worked in just a handful of best case scenarios. in this real world, u wouldnt go far boy.. fuck offf

  18. 18

    Sean McCambridge

    September 16, 2008 12:15 pm

    @web veteran – chill out.

    Good intro to jQuery for beginners. Though I’m not sure the author has it right in his $(‘document’).ready() explanation. The good/bad thing there just doesn’t make sense. I love jQuery, but the great thing about it is you can still mix in naked JavaScript when you need to. Writing JS from scratch is still fine. So it’s misleading and vague to say you absolutely should put an alert() under document ready.

  19. 19

    Hey guys,

    uhh busy day/night workin’ therefore I really cant write alot:

    @web veteran – REALLY chill out man.

    @Sean McCambridge – I definately understand what you mean bro and Im even more newbie to jQuery as youve been 2 years ago – no kidding ;)

    Having just said this I can also say that I really like the structure of the Article. Its enough Information in general for someone starting at jQuery to get his hands dirrty and have some rock and roll with the framwork. I guess if your into jQuery for a while youd argument into what “best practices” would be but then again, an Article always shows the opinion of an author, nothing new.

    Thanks alot Smashing, and Alex

  20. 20

    Why jQuery? You could of made this article non-specific to a framework and it could of appealed to a much wider format. jQuery is one of the worst performing frameworks (not as bad as Prototype or YUI), but no where near the scale of Dojo or Mootools.

    Also the scope of the title seems strange. You are only talking about JavaScript relating to the DOM, otherwise you should mention things like prototype functions, classes and scope of variables which are much more important in getting right rather than defining the onclick event in the HTML.

    Sorry to be so harsh.

  21. 21

    very good article.
    Thank you.

  22. 22

    @ Daniel, personally I see why you admire MooTools. I mean its a powerful framework but pretty hardcore to learn if you arnt intermediate or already pro with JavaScript.

    Im A Newbie in JQuerry and if there is any Name calling like Junior, or of No Idea Kido, let me know and it will be my next Name for this Article, Any Suggestions? Bring it on.

    anyway back to your comment Danniel, The Article in my subjective opinion just gives an introduction to jQuery and some more Info on the framework and the good handling of it.

    cheers mate

  23. 23

    First of all, great article! You guys keep amazing me with really interesting articles.

    Second, is it just me who sees almost all of the code snippets twice? With 4 exceptions, I see every codebox twice, and I’m not drunk ;)

  24. 24

    Hummm…i losted a little time to find the “7 errors game”…heheheh

  25. 25

    @ Sylvia, nah you arnt drunk, I see the double code snippets too. he he…

  26. 26

    great article but too jQuery specific

    Rule #1 agreed but for all JS: unobtrusive JS
    Rule #2 good markup should be provided by some server side coding
    Rule #3 same as #1
    Rule #4 depend what you want. If dealing with DOM objects prefer the ready() (but this is too jQuery specific) else depends
    Rule #5 seems to me like SEO hacking. If something needs to be hidden, by default, I would prefer the CSS solution (since Google sort of understand css but not JS). I’m wondering why someone would put extra code for something that will be hidden…

  27. 27

    Is there a reason for some of the code being written out identically more than once?

  28. 28

    Awesome post.. as usual

  29. 29

    Wow.. you guys are great! Superb article! very very useful! Thank you!

  30. 30

    Jquery is going to be built into my new CMS system which already uses smarty PHP and my new css lib addition.
    come over and have a look

  31. 31

    Alexander Schakel

    September 16, 2008 2:39 pm

    Super! Great article, keep it going!

  32. 32

    I’m still waiting for WHY jQuery.. give us a good and valid reason to USE jquery instead of other libs.. Everything that is in this post can be done by ALL other librarys, and some can even do it better and faster..

    Really, name something, i dare u give us a VALID reason. What makes jquery special and better than the rest of librarys. This post is more about advertising jQuery and shows only stuff that other librarys can do to. I really don’t think this SM worth.

  33. 33

    patrick h. lauke

    September 17, 2008 12:49 am

    under “Rule #3: Accessible and Semantic Markup Comes First”…you have accessibility in the title, but nonetheless fall into the trap that I see far too often with jquery uses in the wild.

    based on your “bad markup” examples, it looks like the desire here is to trigger some behaviour when the TD elements are clicked. now, your “good” example cleans up the markup, but doesn’t solve one fundamental issue: if you attach an onclick handler (whether in the markup itself, or cleaner via appropriate selectors and addEvent) to anything that does not normally receive focus via keyboard (a link, button, image map area), it will be completely inaccessible to keyboard users….no matter how clean your markup is.

    i see this all the time in tutorials, jquery plugins, etc. so, as part of the whole “Accessible and Semantic” slant: if you want users to be able to trigger a behaviour, don’t just attach onclick handlers and such to any arbitrary element (a div, a p, a td, whatever) – otherwise you’ve just made your page completely useless for keyboard users. semantically, if something triggers a behaviour, it should really be a button element…or, at a stretch, a link.

  34. 34

    On that last example.

    Really one should have…
    in css
    .js .selector { display:none; }

    id of “your-site-title” on body tag.
    and a script tag immediately after with the following:
    document.getElementById(‘your-site-title’).className += ‘ js’; //for js specific css

    This is so if js isn’t available the user can access the information.

    Sorry for the lack of tags, the comment stripped them.

    @web veteran: you’re are so crazy. I would hate working with you lol :)

  35. 35

    jquery really rocks! Thanks guys for the tips :)

  36. 36

    edouard duplessis

    September 16, 2008 5:11 pm

    jQuery rule… i used mootools before but I prefered jQuery …

    and for the benchmark… jquery is very fast… and very light

  37. 37

    I used PrototypeJs a number of times in the past. But wow, jQuery can do a lot more by the looks of it.

    Very, very tempted to rewrite my scripts in jQuery…

  38. 38

    The second option will select every <div> that has the id attribute set to mydiv.

    since it’s an id, there should only be one on the page, so saying “every <div>” is silly. Further, its its not even <div>’s , just the single element that has mydiv as its id (regardless of if that element is a <div> )

    Other than that, great article

  39. 39

    this is very very perfect!!

  40. 40

    @SamSam, your point in general is a good one. However, there may be times when specifying the element that an ID is assigned to is necessary. For example, if you’re using the same script on multiple pages and one page has <h2 id=”title”> while another has <h3 id=”title”>, you might need to specify $(‘h2#title’).

  41. 41


    How about Prototype, Mootools, Dojo, … ?

  42. 42


    September 16, 2008 8:42 pm

    the first hides the element instantly while the second fades it out gradually

  43. 43

    Yeah, great article! I have to learn JS soon, so this will help me for sure.. :)))

  44. 44


  45. 45

    Smashing JQuery!

  46. 46

    Armin Cifuentes

    September 16, 2008 10:20 pm

    Nice article! I was trying to learn some MooTools… Now I want to learn jQuery. But, which one should I choose? Wich one ist best for what applications?

  47. 47

    Very useful, thanks! ^^

  48. 48

    this is a really SM artical

  49. 49

    Nice Articile , Thanks Lot

  50. 50

    Great article, especially for beginners (although I liked it too)!

    @Armin Cifuentes: It doesn’t really matter which framework you use since it’s a personal choice. Although MooTools is more for the design side of the website (graphical stuff), while JQuery is more useful for handling the data on the screen.
    Also JQuery is more mature and has more plugins on the internet.
    I would say to start with JQuery and learn how to use it properly. When it all works you can add plugins and/or use other frameworks for specialized functionalities.

  51. 51

    Good article. I use jQuery for a while. Some of the directions will be useful for me.

  52. 52

    Thanks for the comments guys. I’m going to try and respond to a few points… sorry for the long comment..

    @Seth (#11)
    Well picked up… i was trying to make the bad examples as bad as possible ;) and the language attribute is a really common mistake.

    @nicerobot (#14)

    It seems strange to me that you mention a few times about never depending on javascript in an article about a javascript dependent package.

    Not at all. That’s the whole point behind the concept of separating the behavioural layer from presentation etc.

    Yes, it’s important to design your webapp to behave properly in a javascript-less environment but to say to NEVER depend on it a little extreme in this age.

    Actually, there are plenty of corporate environments that have blanket javascript-less environments..

    There are simply webapps that can not be implemented as markup. Games for example.

    Games are unlikely to fit into the realm of requiring accessible content. Obviously, yes, there are situations where the theories i’ve outlined will be too restrictive, however for web sites (in the traditional sense) – i would still argue that the “never” depend on javascript rule holds true. You’ve used the word webapp a couple of times, and a web app is a slightly different use case to a website i suppose.

    @web veteran (#17)

    I think article is hogwash.. its written by someone who has obviously worked in just a handful of best case scenarios. in this real world, u wouldnt go far boy.. fuck offf

    I almost didn’t bother replying to your “comment”. If you have nothing constructive to offer.. bite your tongue. Of course if you DO have a point, feel free to express it… I’d love to hear what you have to say… if the assumptions you’ve made in your comment are anything to go by, it should be entertaining to see you try and actually formulate a sound argument.

    @Sean McCambridge (#18)

    Good intro to jQuery for beginners. Though I’m not sure the author has it right in his $(’document’).ready() explanation. The good/bad thing there just doesn’t make sense. I love jQuery, but the great thing about it is you can still mix in naked JavaScript when you need to. Writing JS from scratch is still fine. So it’s misleading and vague to say you absolutely should put an alert() under document ready.

    Writing JS from scratch IS still fine, however whenever there is a choice between writing our own code and using a framework method to achieve a goal, I would argue that we should use the framework (which is already tested across multiple browser implementations etc..)… why reinvent the wheel?

    But to answer your question, in the case of an alert, it doesn’t need to be in the document.ready, the point i was trying to illustrate was HOW document.ready works (without scaring beginners of with a complicated code example)..

    @Marin (#28)

    Rule #5 seems to me like SEO hacking. If something needs to be hidden, by default, I would prefer the CSS solution (since Google sort of understand css but not JS). I’m wondering why someone would put extra code for something that will be hidden

    Marin, i think you missed the point. The reason why the CSS solution is bad is that it will work even if Javascript is disabled, which leaves the Javascript-less user without access to that content. Moving the hiding implementation into Javascript is the key to degrading gracefully…

    @Michael Thompson (#77)

    With jQuery’s chaining, there’s no need to set something as a variable and then manipulate it.

    With the possible exception of code readability, you’re quite right.

    @V1 (#61)

    Really, name something, i dare u give us a VALID reason. What makes jquery special and better than the rest of librarys. This post is more about advertising jQuery and shows only stuff that other librarys can do to.

    Valid reason: I LIKE Jquery, I also USE Jquery. I dare you to give us a VALID reason WHY NOT Jquery.

    @Stevie K (#69)
    Agreed. Learning JS IS definitely a benefit. It wasn’t my intention to suggest that RAW Javascript is bad, however if you’re

  53. 53

    “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.”

    When you’re using unobtrusive scripting, you can safely move all your scripts to the bottom of the page, to greatly improve performance through progressive rendering and download parallelization.

    See this section of Yahoo’s “Best Practices for Speeding Up Your Web Site” series.

  54. 54

    Just to point out something: this assertion is, in fact, not optimal usage of JavaScript:

    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.

    Reason being: JavaScript should be in external files, yes, but they should not be included in the head of a document, because it actually slows down the loading of a page. Optimal usage would be to include the JavaScript file at the very bottom of the document as the last element. This is not always possible due to scope, but it is highly recommended.

  55. 55

    WOW, very helpful. Thanks a lot.
    Greetings from Austria.


  56. 56

    Amazing!! will get started with JQuery today!!

  57. 57

    @Craig > you’re right, JS should be included at the bottom of the document because scripts in head freeze the document until they’re completely loaded… which can be pretty long when a whole library is included !

  58. 58


    Whats wrong with you, he just gives some advice on how to use Jquery because thats what hes using. And he also explained, that he thinks its ideal because of the low learning curve.

    Why dont you write your own article about javascript frameworks in general? I dare you to mention one good reason why you dont write an article on the topics you like to see covered.

  59. 59

    JQuery is yummy!

  60. 60

    Was kinda hoping you would go into more advanced stuff further down, involving the best practices when coding and use of classes but nevermind. Good for beginners I guess.

    The article however does come across as portraying raw javascript as bad, when it can perform all of the examples unobtrusively, with longer code. I don’t want beginners to get the wrong idea, it’s always best to learn javascript first and then use JQuery to reduce production time.

  61. 61

    Mootools. ;-)

  62. 62

    i hate mootools

    Movie Octopus rules

  63. 63

    One typo…

    should be
    under Understanding Selectors: the Backbone of jQuery
    (not in the <code> block, but in the explanation)

    I love jQuery

  64. 64

    “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.”

    Wow, didn’t anyone catch the missing part of that sentence at the end of “rule 1”?

  65. 65

    Hi there,

    I have a quick question regarding a problem I have stumbled across using jquery and which the above post does not allow for.

    You state above that it is best to

    never include Javascript events as inline attributes.

    and instead target the a tag via a click event provided via jquery through an external file.

    Semantically this makes perfect sense however what do you do when you need to pass in dynamic variables to your jquery function. As far as I can see, you have to use an inline javascript event to enable you to pass variables into your jquery function.

    onmousedown=”newFunction($variableOne, $variableTwo)”

    I know this is not really a forum and so apologies for the post, but being an avid user of JQuery I would really like to know whether there is a way to remove the inline javascript from the page but still pass ther variables to the function.


  66. 66

    Michael Thompson

    September 17, 2008 5:48 am

    With jQuery’s chaining, there’s no need to set something as a variable and then manipulate it. Change this line:

    var goodDay = $('p[title="Good Day Message"]');
    goodDay.text('Good Afternoon!');

    To this:

    $('p[title="Good Day Message"]').text('Good Afternoon!');

  67. 67

    I think you’ll have a much better chance of getting a satisfactory answer and will be able to follow up with additional questions more easily if you direct your question to the jQuery Google Group.

  68. 68

    I have forbidden all java actions on my browser, and I leave a website immediately, when I see that its maker is technician who wants to put all the programming he wasted hs livetime with in a tasteless design. There are millions of these site out there. Make good cntent and good design instead.

  69. 69


  70. 70

    Juan Pablo Barrientos Lagos

    September 17, 2008 7:53 am

    Rlly great article. Thx u.

  71. 71

    The non-Javascript user is missing out on our welcome message.”

    Maybe the non-javscript user enjoys missing out on the web, never mind the welcome message. :D

  72. 72

    Thanks for the comments Alex Holt.
    long but really good.

  73. 73

    Thanks for making it much easier to understand how javascript best be used!

  74. 74

    Thanks for the response Alex.

    That’s the whole point behind the concept of separating the behavioral layer from presentation

    Right, this separation is probably always preferred. But to say “never depend on javascript” is too heavy handed. It should be up to the designer to decide whether it should or shouldn’t be a requirement. I think you’re examples nicely show ways to approach it but “never”, it just too absolute for me.

    Also, no mention of the noscript tag?

    … for web sites (in the traditional sense)

    To support interactive and robust usability features currently requires programming. If we ever have a standard markup for data bindings and validation, it’ll go a long way towards removing that dependency but i don’t think that’s even on the horizon.

    It really just boils down to there being many models for site design between content delivery (traditional) and fully interactive (programming). If the content is not interesting or important without the interactivity, i’d choose to require javascript.

  75. 75

    I stopped paying attention to this article after reading the code example for rule #2 (never rely on JavaScript).

    Firstly – the title attribute should never be used for JS hooks as they can be used by screen-readers to provide extra information about the element and “good-day-message” is no better than the content.

    Second by changing the text value of “good-day-message” to “good afternoon” all semantic reasoning behind the title attribute is lost! Better to use a class for this kinda stuff.

    I’m all for semantic mark-up like you later talk about in your article but that’s just not right…

  76. 76

    For rule #3, how would you pass additional arguments to your function call?

  77. 77

    @ Alex Holt

    hey there, why dont I get a sugestion from you towards my Feedback and opinion about jQeury :( oh and by the way, your a pretty good writer in my very subjective opinion mate ;)



  78. 78

    @bruno sorry.. you were too nice! heheh. Thanks for the feedback..

    @Dave it depends what sort of arguments you actually want to pass… but why not use selectors to get the data inside your function call?

  79. 79

    Its a very useful post for an upcoming JQuery Developer.
    Thank you for posting such beautiful articles.

  80. 80


    A lot of developers get caught up on that one. The way to accomplish this with jQuery is as follows:

    return myFunction( myArg1, myArg2, myArg3 );

    You can also pass the event type and the element that called it through to your returned function, which is useful if you want to continue accessing it:

    $("#myElement").onmousedown(function( i ){
    return myFunction( myArg1, myArg2, myArg3, this, i );

    Your variable “i” is the reference to the event, which is mousedown, while “this” will reference #myElement.

    One thing to note is that you don’t need to bother with:

    // some code here...

    When you have the following shortcut:

    // some code here...

    The reason jQuery’s ready() method is helpful is because it does not rely on the window.onload event. This event can only be assigned once to a function, which means if you use it again you are reassigning it, and you lose your previously assigned onload functionality. jQuery uses a DOM ready approach, which has the additional ability to support multiple DOM ready calls. So you could have this:

    // some code here...

    and then have this further down in the document:

    // some more code here...

    Both will be called when the DOM is ready.

  81. 81

    Wow, it’s interesting. I never think like this before. Thanks anyway

  82. 82

    great article but the jquery site is just not working….

  83. 83

    Thanks for your awesome article. It’s very useful for me.

    But I wonder if you call jQuery is a framework, I don’t think so. I means jQuery is a library for me to build my framework. Anybody with me?


  84. 84

    this site has javascript errors… interesting.

  85. 85

    Thanks for the post, it really made me realize that jQuery is not that difficult to learn.

  86. 86

    Rule #1 says “seperate javascript functionality” yet SM’s own code snippet areas are full of <a onclick=”function()” href=”#”> for the view plain, copy to clipboard, and print links.

    Practice what you preach!

  87. 87


    I’m with you.

    I still want to access all the benefits of OO and don’t want to reduce an elegant javascript API to a whole lot of in-line procedural programming on a page by page basis. I rather use JQuery in two modes:

    1. As a utility class that I utilise within my own objects
    2. As a base class – then I write a JQuery plugin.

  88. 88

    Great article! Very informative.

  89. 89

    JQuery is not a good choice for a Javascript framework. Their licensing model is a mess and their ongoing development and support is almost non-existent. Dojo and/or Prototype (scriptaculous) are far better frameworks with more functionality.

  90. 90

    @Ross Bruniges true that.. to make that snippet more semantically correct i suppose the title should have been a useful description of the content. I was more focussed on trying to communicate that jQuery allowed you to select using attributes over and above just class and id. But yeh, in hindsight I’d concede that it’s a pretty dodgy example – btw: i’m glad that despite losing interest you DID read on :)

    @neps in theory you’re right. But the code snippets use a javascript package to generate that coloured markup content… If you disable javascript you will see that that content is not even visible, instead that content is in fact marked up as a pre tag.

  91. 91

    Russell Heimlich

    September 18, 2008 9:42 am

    I have a big issue with the last example. Why on Earth would you need a seperate jQuery plugin to write CSS on the fly? The better thing to do would be to write specific CSS for that class and apply the class using JavaScript. The jQuery would look like this:

    .selected { ... whatever styles you want to put here in the stylesheet ... }


    Mixing in presentation (CSS) and behavior (JavaScript) is just as big of a no no as using a table in place of a definition list (DL). See Rule #3 above!

  92. 92

    Oops – forgot to mention you should check out jQuery’s discussion group for support, it’s got tons of people who are nice, knowledgeable, and willing to help.

  93. 93

    @Alex Holt that’s my point but the example might be confusing

    The hidden paragraph looks like a spam technique.

    I would recommend to use that technique to hide tabs contents/subnav layers, some content that will be shown by a click event.

  94. 94

    To add on to Alex C.’s argument, I think jQuery is a great library to use because of it’s legibility. One of the hardest things about development can be adapting to someone else’s coding style. This can be especially difficult with JavaScript because it is a loosely typed language.

    I’ve found that jQuery makes JavaScript much more understandable, and hopefully this will help future developers who work with my code.

    Kevin Leary

  95. 95

    very informative, good job as usual!

  96. 96

    Sometimes the Separate Javascript Functionality doesnt work, you need to add onclick when you are printing a html/javascript code via ajax, for example when your reload a chunk of html code with javascript and events inside, you must use onclick otherwise jQuery will no work.

  97. 97

    @Russell Heimlich (#106) The reason for using the plugin to write CSS on the fly instead of dynamically attaching a class to the elements is that your method requires the DOM to be ready in order to select the element and attach the style. In many instances this causes a presentational flicker after the page has loaded, where all the elements with your hide class will dissappear – this A) unattractive and B) confusing to the user. However using my method, the rules can be inserted into the stylesheet before (or while) the DOM is loading and they are actually rendered invisible. No flicker. Obviously there will be cases where it would be fine to work the way you have suggested, without the plugin, but this example probably isn’t one of those cases.

    @roberto that’s not really true. Unless I misunderstand you, there’s nothing to stop you from using AJAX to load (or reload) chunk of HTML code, and then after the AJAX load has finished it will fire an event. You can use that event to attach your events into the HTML that you’ve loaded…

    This leaves you free to write the HTML that you are loading from AJAX using the same separation and semantics as outlined in the article and then to add the behavioural layer from javascript.

  98. 98

    I use mootools AND Jquery. With this I get the best from both worlds and don’t have to choose!

    More info on how this is done can be found on

    I can’t really say one is better than the other. They are 90% the same, speed wise it’s about milliseconds. When firefox 3.1 and google chrome becomes stable the difference won’t mater anymore as JS the engines will be much stronger and won’t need that much ‘optimizing’ anymore.

  99. 99

    Excellent! jQuery is a scary thing no more. :)
    Thank you!

  100. 100

    Good article but i have to say something…
    jQuery is simple and good for beginners of javascripts and little webapps. But in a complicated application, it’s recommanded to keep a hand on all your js. So jQuery could be good but could be a handicap if there’s a compatibility problem. I think as exemple if an item has two or more css classes, if document.onmousemove changes during your page living…
    If an ajax request rewrite your innerHTML, does the jQuery reassign bindings between items and js functions…

    A lot of questions we have to ask before using “free downloadable stuff” for our websites.

  101. 101

    jQuery sux, I really don’t understand why this shitty library is so popular.. strange API, it’s easy to make mistake in those stupid function chains, fucked up unintuitive documentation and overall quite limited features for 94kb (uncompressed).. in my opinion mooTools is ten times better than jQuery, much more elegant and friendly with clean API

  102. 102

    Nice and impressive article. Nice examples, simple writing makes easy to understand the features.

    thanks to the author.

  103. 103

    If you do not call the method inline onclick etc, then you have to traverse the DOM to bind it to that link (or div etc) adding overhead. Also for another designer viewing the code, it would be hard to judge if there is a function bound to a particular Dom object by looking at the html.
    Also when dealing with a large site, waiting for the document.ready() function to call may take a while, for eg In that case clicking on something will not trigger the desired action without a considerable lag.
    In such circumstances is not better to avoid the unobtrusive DOM method. Instead make the function call as simple as possible and pass in $(this) as reference. This way you avoid traversing the DOM and you have reference to the caller element. Also this way anyone else working on the code will know that there is a function attached to it.

  104. 104

    I agree with comments 44, 59 and 60.
    An ID must be unique within the DOM, so returning every element with a given ID doesn’t make sense. There should be zero or one matching element.

  105. 105

    Excellent jQuery examples and explanation. Recently I joined new office where they have put a lot of efforts in jQuery and its plugins. Almost everything and anything you can possibly do with jQuery while keeping in mind what we call web standards. Even pretty flash effects can also be made with jQuery. Its time saving and effective and cross browser.

  106. 106

    Excellent article. Till date i was stunned on seeing some web2.0 sites with effects and when i check the view source nothing will be there to track. But today only i came to know that trick.

    Smashing Magazine Rocks !!!!

  107. 107

    It’s really cool article for JQuery lovers.

  108. 108

    please add me to the email list

  109. 109

    This article is a good introduction to jQuery.
    Instead of using the above mentioned jQuery cssRule plugin we can simply use:

    $(“element.className”).css({display: “none”});

    Corrections are welcome.

    Thank you for this article.

    enjoy :)

  110. 110

    I love jQuery. I have been using it for some time now. It still amazes me that people argue back and forth on javascript frameworks. If you don’t like a certain framework, don’t use it, and if you know the article is about said framework, don’t read it!

    Really, it’s like people go out of their way to argue when they could be making a cup of tea or something. =D

  111. 111


  112. 112

    gr8 ,very easy to understand the basic of jquery

  113. 113

    Worthless (like jQuery.) Same for MooTools and the rest. Browser scripting and general-purpose libraries do not mix. Furthermore, jQuery is some of the worst code I have ever seen (in any context.)

    Wow, you can write terrible, incompatible and grossly inefficient code in less lines (typically indecipherable), without actually learning anything (except how to use jQuery.) Certainly your clients will be put off when they start losing leads (due to the incessant browser sniffing), but you will have already cashed your check, right?

    Learn the Javascript lanaguage and acquire some experience with browser scripting before you decide to jump in with both feet (with somebody else’s anchor around your neck.)

  114. 114

    Nice and impressive article.
    thanks to the author.

  115. 115

    pradeep pathak

    January 2, 2009 3:39 am

    I have been working in php for last 1.3 yrs. Always wanted to have some effects that look good and should work efficiently. As a plugin jQuery works fine. I m a newbie and trying to get something through the article. Its really good to read. It was a good start for me after going through the article. If any further query could be entertained in personal I would be highly thankful to the author. Any ways its great!!!

  116. 116

    Rukhsar Ahmad

    January 15, 2009 9:35 pm

    Nice article and easy to understand Jquery

  117. 117

    @David Mark – I’ve been writing javascript code for like 9 years… i’ve more than learned the language, thanks for the advice though.

    To be perfectly honest.. i’m not that interested in what’s going on behind the scenes in a framework that I’m using.. especially when it cuts development time down to almost nothing… if it doesn’t suit you.. that’s fine… although by the same logic.. why don’t we program all our websites in assembler and build custom database solutions?

  118. 118

    great post.

  119. 119

    @Alex Holt – Clearly you still have much to learn, which is probably why you depend on jQuery and not your own code :P. If nothing else is a better example of this, than it’s in the suggestion that you ditch CSS to add CSS rules in javascript? That is about the dumbest thing I have ever heard, and you don’t need to know much about Javascript to know that.

  120. 120

    You need to branch away from jQuery for a bit there. You seem very dependent on jQuery which is not good at all. What happens when you are assigned a project and the client, web master, or anyone above you, says you cannot use jQuery. You will truly be lost. This is not a comment to harass you i want to merely encourage you do learn JavaScript. I have one reason why im not a fan of others using jQuery and im starting to see it more and more. People think they know what the hell they’re doing but in reality they don’t.

    First off dont create CSS on the fly to be applied to your markup. That is dumb.

    you can simply do:

    .none {

    then with jQuery:

    $(“div.myElementsClassName”).addClass( “none” );

    adding rules to styleSheets with javaScript is never a good idea. The only time i have ever seen a use case was for a site where people can create their own layouts (with charts or pages or whatever), and save those as settings for the next time they visit the site. But even then there are other ways.

    Another reason why less experienced people should not be jumping into writing jQuery is the fact that it is going to flat line your learning curve. In your examples you show some very procedural code writing:


    //do something


    This is horrible syntax. and im sure your code gets quite messy and hard to follow no? Keep it Object-based.

    var MenuItems = function(){}

    MenuItems.prototype.addEvents = function(){

    var self = this;

    $(“#myElement”).click( self.openLink );


    MenuItems.prototype.openLink = function(e, el) { this.href ); //or whatever


    var MenuItems = new MenuItems();

    …clean and simple.

    in conclusion, please learn more about “Native” JavaScript before advising others. As for
    jQuery, i love it, but its use it to speed up code development, handle cross-browser issues, and keep you from replicating code. If you are in experienced with OOP methodology and the internals of how jQuery works, you could get yourself into a BIG mess. Not to mention your lack of ability without it.

  121. 121

    I beg to differ on #2.

    Although this is a great tactic for handling multiple items, I think it may be a bit wasteful when using it on just one link. There were several talks on YUI theatre, showing that the largest amount of time consumed is on DOM manipulation and not the actual javascript. You need to query the DOM each time you need to use that function and then you have to observe all click events and check whether they came from the proper element. So, it may be useful a good amount of the time, but it’s not the catch all.

    i consider myself an intermediate programmer, so I may have misquoted or misrepresented something. If I have, please let me know.

    Edit: You’re not using any observation for that particular method, so I stand corrected. The thought still holds true for the manipulation of the DOM.

  122. 122

    Totally agree with Mike (comment 137).

  123. 123

    i cannot agree on the standards you are setting up here. rule number 1 is the worst attempt to set up practices ever. You rule: Never include Javascript events as inline attributes. This practice should be completely wiped from your mind. Formulating such a rule has disqualified you to participate in any real world operation that deals with javascript on a professional (real world) level. That rule #1 of yours will work for the one or two examples you are giving, but you don’t even consider stating that this works in these limited cases only – and you fail to inform the audience that there are many cases where inline events are the only way to go. What you do by setting up rules appears to me shows a rather limited approach on programming javascript solutions. This is not bad, and if your javascript is about rollovers or image replacement, or navigations, well yeah, even then your rules do not apply.

    Of course:
    THIS [a href= “#” rel=”nofollow” ]Click![ / a ]
    can be replaced by
    THAT [a href = “backuplink.html” rel=”nofollow ” ]Click![ /a ]

    THAT does not relate to THIS, because by doing THAT you don’t just do THIS anymore, you do THIS AND something ELSE, following a link, which THIS was not about.

    The bad markup vs good markup directive appears to me based on a rather personal way of organizing things, and that is fine. But you cannot declare it a method by a few rules, as it is not the real world approach, as the examples you give are just very simple and limited, like “hello world” – which is not very demanding. The many variations of how a script is called and how the content of a DIV(and inline markup) can be changed by javascript and ajax calls makes me wonder how complex your projects are, how much you can depend on setting up rules that rule out so much and will never hold up for hundreds of functions and bundles of dozens of events on pages containing hundreds of lines of such bundled elements, like a shop, or a tracking system. Your examples do not include parameters, that might be passed in arrays, and what about an interface where there is multiple menus generating and manipulating the content on the fly and changing the parameters of the lets call it “onclick thingy” that you want to eradicate?

    Another of your “rules”: This means storing ALL Javascript code in external script files and building pages that do not rely on Javascript to be usable. – That sounds like an architect saying: there is no need for windows in my houses, as i will install superiour artificial light sources in all of my structures for them to be illuminated whenever they have to be illuminated, because only then the light is usable at the command of those that are inside the structure, only then it is good markup. Why would you then even bother using javascript, why even build a site with it?

    I can only suggest to anybody out there who has no clue about javascript: inline calls are just the way to go as are other methods, they are reliable and allow for quick implementation where they are needed. Do not follow clumsy rules just to have followed rules, but implement what fits your project, even if it is “dirty”. So my rule is this: make your own rules, create your own libraries, learn from jQuery. But you don’t have to adapt your javascript to “fit” jQuery, as this could end up in being a waste of time, as jQuery is just another layer that can be replaced easily, by your own library, or another great layer.

    And make your code easy to be understood by others, it will make collaboration with coworkers and web designers much easier, as they will be able to understand, to adapt, make changes, without going through a maze of linked documents.

  124. 124

    Great article!
    It’s really helpful, I’ll suggest this page for all of my web-developer friends…

  125. 125

    “I’ve been writing javascript code for like 9 years… i’ve more than learned the language, thanks for the advice though.”

    You are like, still completely clueless, dude. :)

    To wit:

    “To be perfectly honest.. i’m not that interested in what’s going on behind the scenes in a framework that I’m using.. especially when it cuts development time down to almost nothing… if it doesn’t suit you.. that’s fine… although by the same logic.. why don’t we program all our websites in assembler and build custom database solutions?”

    Statements that start out “To be perfectly honest” or “I’m gonna tell you the God’s honest truth” invariably turn out to be lies so blatant that they insult the intelligence of the reader.

    Your statement about assembler and databases is incomprehensible. What are you trying to say?

  126. 126

    Nice article but using dt and dl for option lists is not very nice.
    There tags are meant to be used for glossaries not for option lists…

  127. 127

    Great article. Thanks
    jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery

  128. 128

    Really awesome article man.. I Love JQuery….

  129. 129

    oh God.
    I totally LOVE this article.

  130. 130

    unique article

  131. 131


  132. 132

    Phillip Matthew

    May 26, 2009 8:44 pm

    Iam best at handball you want beat me?? (NOPE SORRY)

  133. 133

    Phillip Matthew

    May 26, 2009 8:46 pm

    Yes i am a pretty girl in ACT, Canberra , Australia You want puhnnani??

  134. 134

    Amazing article, thanks!

  135. 135


    June 3, 2009 11:46 am

    This article is rather non-creative as it only describes ementary things done in a more DOM-way. jQuery got to be more than xhtml-strict-fanboys head-quarter.

    Appriciate your effort, but for me it’s back to google…

  136. 136

    Can i use this article in my website?

  137. 137

    good post. it really helps me :)

  138. 138


    July 6, 2009 5:35 pm

    Just when you take a breath and mumble, “Yeah I got this!” You magazinesmashers remind us tag-a-longs that learning web design is like the horizon, the goal is always just beyond our line of sight. The implications here were not good, they were great!! Thanx for the terra firma.

  139. 139

    Excellent if not obvious best practices but not always practical or necessary. The majority of applications are business applications where the client can be stipulated: must use a browser that supports JavaScript and CSS. Creating a pure HTML solution is a colossal waste of time and money. Even for public sites, I have no problem stipulating that you must have CSS and JavaScript. Interweaving support for visually impaired users is equally asinine. Instead, make them a completely separate site geared toward audible navigation and screen reading, rather than pretend you’ve actually done them a favor by adding 508 compliance.

  140. 140

    i built an animated and fast “search in this page” search engine by using the “:contains” selector of jQuery:

    mix of js and jquery syntyax:

    function search {
    var word=document.getElementById(‘mysearchbox’).value;
    $(“div:contains:(” + word + “)”).show(200);


    div {
    display: none


    it contains some bad markup but it works and developable.

  141. 141

    bad and worst .. i never sean such a worst article in my career…..
    don’t try to publish this kind of article

  142. 142

    I am looking for an example of a complete jQuery web project, not just examples to accomplish a specific task, but instead a project demonstrating “best practices” for an entire site using jQuery. Ideas?

  143. 143

    All a bunch of bullshit. You don’t even give reasons for half of your “bad” “good” lists. Just glorified opinions from a script kiddie.

  144. 144

    Yes, that great JQuery, we can do more effective coding by using JQuery.

  145. 145

    From my point of view, some opinions are a little bit idealistic. However I guess that depends on the project requirements. And I agree JQuery is concise and effective.

  146. 146

    Your article rocks! I wish every article which talked about Jquery an JavaScript were like this…

    Thanks a lot.

  147. 147

    Obviously, the syntax
    jQuery.cssRule(“p.hide-me-first”, “display”, “none”);
    is more complex to understand for a javascript programmer than’none’;
    (where obj is the object of course)
    Why do more when you can do less ? Style is the standard css attribute in Javascript.

    Use standard commands when there are simple.

  148. 148

    Very good articles for the newbie !!!!!!

  149. 149

    So you want to replace:

    <a href=”#” onclick=”doSomething()”>Link!</a>


    <a href=”#”>Link!</a>

    And the only way to know that clicking Link! will call “doSomething()” will be to look deep down in another file somewhere else?

    How is that design cleaner? Sounds very sadistic IMO.

  150. 150

    Eric: The difference is, my code rewrites the rule in the stylesheet, yours alters the style on an object.

  151. 151

    yes i love jQuery , i am still learning this particular stuff but i would suggest that this would be a great alternative to JavaScript coding .

  152. 152

    php customization

    June 21, 2010 10:52 pm

    This article is using to clarify my client doubts.
    This is is nice script.. Its help to improve the beginner knowledge..


  153. 153

    Salsan Jose

    June 22, 2010 4:39 pm

    I liked your simplicity of JQuery presentation. It would be great if you can write about Javascript Prototype framework best practices .

    Salsan Jose

  154. 154

    “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.”

    To be frank, this is unrealistic from a number of perspectives.

    1) For one thing, the very way that jQuery works tends to discourage building apps that won’t work without javascript.

    2) If I didn’t think that users would have javascript enabled, I wouldn’t use jQuery in the first place.

    3) Building backup code to provide 100% functionality for users without javascript may not be practical (or even possible).

    4) Half the sites on the net won’t work without javascript, so it’s not like this is an uncommon state of affairs.

    In short, if they want to use my application, they’ll have to enable javascript. That’s a requirement, the same as using a browser that supports images or CSS.

  155. 155


    As far as i know .hide() adds style=”display:none” to an object.

    .cssRule adds a property to the whole class.

  156. 156

    Great article, I agree to most.
    But what about jQuery tabs? or the accordion?
    This is going against the rules shown in this article.
    Using tabs in a browser not supporting jquery and javascript the content looks weird and creepy. I know many sites where tabs are not just used, but almost essential for the concept of it.

    What do you say?!

  157. 157

    Thanks for the useful insight. All points taken, whole heartedly :)

    Just a small point, the example for dynamic CSS rule creation used is a bit inappropriate. At times, you don’t want content to be visible on the page just for no reason at all and make you look foolish. If JS doesn’t work, that content would there, right in the user’s face, no reason, no justification.


  158. 158

    I agree to Mike in all regards. Even in case, the user’s browser crashed a tad bit and wasn’t running JS for that very moment, it’s okay! The user must get it fixed. If JS has been disabled on purpose, then why would the user use my app in the first place? Moreover, users now install JRE, Flash, Shockwave and what not… JS is just a feather as compared to them, not even requiring an install.

  159. 159

    Jquery is really having great dom scripting capabilities, i had experienced.

  160. 160

    Hi priya you told is true

  161. 161

    Very nice points… agree with almost everything except the dynamic CSS rule creation (which was already mentioned a few times).

    In this case, the visibility of something seems more like a presentation issue and IMHO should be handled by CSS (but I admit, this is a very fine line with behaviour, especially when doing show/hide toggling effects).

    However, there are some alternatives to pushing everything through jQuery and hoping for the best… we can use a combination of CSS(3), HTML(5) and Javascript(jQuery) to progressively enhance how the visibility looks/feels (i.e. fades and other effects) but at its base we can also utilize CSS :hover, :focus, and :active states plus display, visibility, and color/sizing rules. See for example these:

    Although, supporting back to IE 5.5 or unpatched IE6 will not be possible, I tend to like the approach of showing users still stuck in the stoneage on those browsers an “Upgrade Suggestion” link… or… in the 21st century do we really need to encourage people to use outdated browsers?

    Cheers, keep up the good work!

  162. 162

    thanks it is great article ………..very important ………….

  163. 163

    thanks it is great article …………

  164. 164

    Nice script…..

  165. 165

    muhammad taahaa

    March 3, 2011 12:35 am

    very good work………..taahaa….

  166. 166

    This is a rather superficial article. It rules out javascript for providing content, which isn’t reasonable in all web applications.

    If you are *only* using javascript to style your page and add affects, then it is fairly easy to provide a non-js version of your content. If this is your goal, then this is a good (albeit self-evident) checklist to follow. However, if your web app is sufficiently complex, this just isn’t feasible.

    In its own limited context, the article is right, but it should be clear about that.

  167. 167

    Kiran Kilari

    April 7, 2011 11:27 pm

    Very useful for the learners…

  168. 168

    It’s obvious you have quite a bit of experince in the field. But what is also obvious that you don’t have quite enough (yet).

    All of your rules(ideas) are correct but a little too impractical for a real life scenario and too idialistic – not fit for reality. The truth is right in the middle of the good & bad suggestions you give which means unfortunatly your ideas are neither good nor bad – sorry but it’s a bit true.

    Let me give you a couple of examples: rule#1: do you know what happens when the next developer comes in and tries to maintain your code ? Well, he has to scramble to find what the heck happens onclick because on click is far far away in a remote file hooked up even more javascript = 2 or more times the work & time for the developer to modify the onclick event which = it’s quite possiable nobody will appreaciate your perfect principles and design but will rather be annoyed. rule#1: javascript is fairly safe and supported for a few years not by all browsers = you can rely on it for functionality as many (if not all) successful websites use it.

    Alright. Not to mention all your suggestions require increased time & space complexity even if it is on the client side = your websites are slower then the bad practices. The rule of thumb is = don’t follow the trend (patterns) but adapt your solution to what you need to achive. Example, if it’s speed by all means use plain javascript, if it’s development turnaround cycle speed use jquery or something along the lines.

  169. 169

    In the past, I have avoided Javascript. One reason for this is that I have always thought Javascript was horrible, ugly code to look at. Using jQuery and the principles discussed in this article actually make the Javascript nice and tidy. Also, with the exception of specific web apps with specific purposes, the concept on having your content available without relying on Javascript is a practice that should be followed much more often. Thanks for a great article.

  170. 170

    great guide for a jQuery noob like myself.


  171. 171

    Nice one..But how do you call an external js file that contains a jquery function from your html..I have a html form and an external jquery function that validates the do I call that function, I have been seaching every where I don’t seem to get an answer: here is my jquery function:

    jQuery().ready(function ()
    var postForm = true;
    if ( $(this).val() == “” )
    if ($(this).attr(“id”)!=”EmailAddress”)
    $(‘#validatortxt_’ + (index + 1).toString()).text(” *”);

    postForm = false;
    $(‘#validatortxt_’ + (index + 1).toString()).text(“”);
    postForm = true;

    return postForm;



  172. 172

    siva shankar

    June 2, 2011 9:35 am

    Thanks for giving this data

  173. 173

    In most points I agree with your opinion, but the last example is suboptimal. Sure, search engines can filter hidden elements and your content can’t be found as good as it’s possible.
    The problem is the view of the user. when there are many hidden elements on the page, it looks always ugly at the beginning. the user can see how the page is build up. not perfect anyway.

    I prefer the first way, because it looks always better for user eyes. when your content is good, people will create backlinks and your page will have a good traffic.

  174. 174

    Thanks 4 diz.

  175. 175

    The second option will select every ⟨div⟩ that has the attribute set to “mydiv”.

    This is wrong! The truth is this will select every element (not only “div”) with id equal to “mydiv”.
    Please update.
    Thanks for great article.

  176. 176

    Very good article! Thank you!

  177. 177

    To say you should not use javascript on your html page and in the same breath to say to use jquery shows the author does not have a firm standing about javascript and jquery.

  178. 178

    JQuery is javascript. The delination between good and terible mark up is not based on a sound understanding of javascript and jquery.

  179. 179

    Muhammad Hussain Wazir

    July 4, 2012 10:11 pm

    This is really help full topic and really enjoy and learn from this.
    Thanks To all for such informational topic sharing.

  180. 180

    Stephani Djojo

    July 16, 2012 6:28 am

    awesome article!! Good coding, good decumentation, good programmer!!!

  181. 181

    What drives me nuts is going into a “legacy” jQuery document and not being able to find the relevant jQuery/JS code for the given markup…. ie: blah — to find out after much research that ‘abutton’ is the class tag used to bind the jQuery action to… I used to have lots of hair, I now have much less for the barber to deal with.

    The end point to take away – jQuery is no more the panacea for “good” web code than is any other methodology.

  182. 182

    Here are some points regarding jQuery best practice….

  183. 183

    This article is AWESOME!!! I never thought there is cssRule. What a GREAT post!!!

  184. 184

    simpal chaudhary

    March 25, 2013 11:23 pm

    Nice article…!!!

  185. 185

    Not SEO hacking, but actually SEO compliance. Back in the day, the trickery was to have inline page text (paragraphs of unrelated keywords) that was hidden via CSS. Users never saw words, but the search engines that did not understand CSS read through them as valid matching terms. Once google started reading CSS, they actually demoted any sites that had CSS-hidden text. Ends up, the proper, modern solution is that it should be implemented as the original article suggests: all page content visible by default, and then for functional/styling reasons use Javascript to hide it after the page loads. This actually makes the most sense anyway, if you are typing content into the page HTML that should not be visible from the start, then maybe reverse your thinking – don’t include it then hide it, perhaps never include it and generate it later (instead of just showing it) using Javascript element creation.

  186. 186

    Carlo Rizzante

    November 7, 2013 2:23 pm

    Instead to use cssRule, one can also add (or remove) a class into the body tag via Javascript, therefore discerning if the browser is able to run scripts or not. That’s basically what Modernizr does, in fact.

    Which, can be changed via script. This way there is no need to add classes to elements via jQuery. One can just properly style via CSS for different states.

    .no-js .my-element { display: block; }
    .js .my-element { display: none; } /* and later activated accordingly */

  187. 187

    I am using lightbox popup window. I am displying a product thumb in my webpage. If anybody click it, it will popup but I unable to add order button to open product’s website to place an order.

    Can you please help me? Can you please mail me its source code?

  188. 188

    I’m looking for a simple program of java script …I want to practice on how to make some programs…


↑ Back to top