
Smashing Magazine we smash you with the information that will make your life easier. really.
jQuery and JavaScript Coding: Examples and Best Practices
September 16th, 2008 in How-To | 166 Comments

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.
1. Why jQuery?
jQuery is ideal because it can create impressive animations and interactions. jQuery is simple to understand and easy to use, which means the learning curve is small, while the possibilities are (almost) infinite.
Javascript and Best Practices
Javascript has long been the subject of many heated debates about whether it is possible to use it while still adhering to best practices regarding accessibility and standards compliance.
The answer to this question is still unresolved, however, the emergence of Javascript frameworks like jQuery has provided the necessary tools to create beautiful websites without having to worry (as much) about accessibility issues.
Obviously there are cases where a Javascript solution is not the best option. The rule of thumb here is: use DOM scripting to enhance functionality, not create it.
Unobtrusive DOM Scripting
While the term “DOM scripting” really just refers to the use of scripts (in this case, Javascripts) to access the Document Object Model, it has widely become accepted as a way of describing what should really be called “unobtrusive DOM scripting”—basically, the art of adding Javascript to your page in such a way that if there were NO Javascript, the page would still work (or at least degrade gracefully). In the website world, our DOM scripting is done using Javascript.
The Bottom Line: Accessible, Degradable Content
The aim of any web producer, designer or developer is to create content that is accessible to the widest range of audience. However, this has to be carefully balanced with design, interactivity and beauty. Using the theories set out in this article, designers, developers and web producers will have the knowledge and understanding to use jQuery for DOM scripting in an accessible and degradable way; maintaining content that is beautiful, functional AND accessible.
2. Unobtrusive DOM Scripting?
In an ideal world, websites would have dynamic functionality AND effects that degrade well. What does this mean? It would mean finding a way to include, say, a snazzy Javascript Web 2.0 animated sliding news ticker widget in a web page, while still ensuring that it fails gracefully if a visitor’s browser can’t (or won’t) run Javascripts.
The theory behind this technique is quite simple: the ultimate aim is to use Javascript for non-invasive, “behavioural” elements of the page. Javascript is used to add or enhance interactivity and effects. The primary rules for DOM scripting follow.
Rule #1: Separate Javascript Functionality
Separate Javascript functionality into a “behavioural layer,” so that it is separate from and independent of (X)HTML and CSS. (X)HTML is the markup, CSS the presentation and Javascript the behavioural layer. This means storing ALL Javascript code in external script files and building pages that do not rely on Javascript to be usable.
For a demonstration, check out the following code snippets:
Bad markup:
Never include Javascript events as inline attributes. This practice should be completely wiped from your mind.
<a onclick="doSomething()" href="#">Click!</a>
Good markup:
All Javascript behaviours should be included in external script files and linked to the document with a <script> tag in the head of the page. So, the anchor tag would appear like this:
<a href="backuplink.html" class="doSomething">Click!</a>
And the Javascript inside the myscript.js file would contain something like this:
...
$('a.doSomething').click(function(){
// Do something here!
alert('You did something, woo hoo!');
});
...
The .click() method in jQuery allows us to easily attach a click event to the result(s) of our selector. So the code will select all of the <a> tags of class “doSomething” and attach a click event that will call the function. In practice, this
In Rule #2 there is a further demonstration of how a similar end can be achieved without inline Javascript code.
Rule #2: NEVER Depend on Javascript
To be truly unobtrusive, a developer should never rely on Javascript support to deliver content or information. It’s fine to use Javascript to enhance the information, make it prettier, or more interactive—but never assume the user’s browser will have Javascript enabled. This rule of thumb can in fact be applied to any third-party technology, such as Flash or Java. If it’s not built into every web browser (and always enabled), then be sure that the page is still completely accessible and usable without it.
Bad markup:
The following snippet shows Javascript that might be used to display a “Good morning” (or “afternoon”) message on a site, depending on the time of day. (Obviously this is a rudimentary example and would in fact probably be achieved in some server-side scripting language).
<script language="javascript">
var now = new Date();
if(now.getHours() < 12)
document.write('Good Morning!');
else
document.write('Good Afternoon!');
</script>
This inline script is bad because if the target browser has Javascript disabled, NOTHING will be rendered, leaving a gap in the page. This is NOT graceful degradation. The non-Javascript user is missing out on our welcome message.
Good markup:
A semantically correct and accessible way to implement this would require much simpler and more readable (X)HTML, like:
<p title="Good Day Message">Good Morning!</p>
By including the “title” attribute, this paragraph can be selected in jQuery using a selector (selectors are explained later in this article) like the one in the following Javascript snippet:
var now = new Date();
if(now.getHours() >= 12)
{
var goodDay = $('p[title="Good Day Message"]');
goodDay.text('Good Afternoon!');
}
The beauty here is that all the Javascript lives in an external script file and the page is rendered as standard (X)HTML, which means that if the Javascript isn’t run, the page is still 100% semantically pure (X)HTML—no Javascript cruft. The only problem would be that in the afternoon, the page would still say “Good morning.” However, this can be seen as an acceptable degradation.
Rule #3: Semantic and Accessible Markup Comes First
It is very important that the (X)HTML markup is semantically structured. (While it is outside the scope of this article to explain why, see the links below for further reading on semantic markup.) The general rule here is that if the page’s markup is semantically structured, it should follow that it is also accessible to a wide range of devices. This is not always true, though, but it is a good rule of thumb to get one started.
Semantic markup is important to unobtrusive DOM scripting because it shapes the path the developer will take to create the DOM scripted effect. The FIRST step in building any jQuery-enhanced widget into a page is to write the markup and make sure that the markup is semantic. Once this is achieved, the developer can then use jQuery to interact with the semantically correct markup (leaving an (X)HTML document that is clean and readable, and separating the behavioural layer).
Terrible markup:
The following snippet shows a typical list of items and descriptions in a typical (and terribly UNsemantic) way.
<table>
<tr>
<td onclick="doSomething();">First Option</td>
<td>First option description</td>
</tr>
<tr>
<td onclick="doSomething();">Second Option</td>
<td>Second option description</td>
</tr>
</table>
Bad markup:
The following snippet shows a typical list of items and descriptions in a more semantic way. However, the inline Javascript is far from perfect.
<dl>
<dt onclick="doSomething();">First Option</dt>
<dd>First option description</dd>
<dt onclick="doSomething();">Second Option</dt>
<dd>Second option description</dd>
</dl>
Good markup:
This snippet shows how the above list should be marked up. Any interaction with Javascript would be attached at DOM load using jQuery, effectively removing all behavioural markup from the rendered (X)HTML.
<dl id="OptionList">
<dt>First Option</dt>
<dd>First option description</dd>
<dt>Second Option</dt>
<dd>Second option description</dd>
</dl>
The <id> of “OptionList” will enable us to target this particular definition list in jQuery using a selector—more on this later.
3. Understanding jQuery for Unobtrusive DOM Scripting
This section will explore three priceless tips and tricks for using jQuery to implement best practices and accessible effects.
Understanding Selectors: the Backbone of jQuery
The first step to unobtrusive DOM scripting (at least in jQuery and Prototype) is using selectors. Selectors can (amazingly) select an element out of the DOM tree so that it can be manipulated in some way.
If you’re familiar with CSS then you’ll understand selectors in jQuery; they’re almost the same thing and use almost the same syntax. jQuery provides a special utility function to select elements. It is called $.
A set of very simple examples of jQuery selectors:
$(document); // Activate jQuery for object
$('#mydiv') // Element with ID "mydiv"
$('p.first') // P tags with class first.
$('p[title="Hello"]') // P tags with title "Hello"
$('p[title^="H"]') // P tags title starting with H
So, as the Javascript comments suggest:
- $(document);
The first option will apply the jQuery library methods to a DOM object (in this case, the document object). - $(’#mydiv’)
The second option will select every <div> that has the <id> attribute set to “mydiv”. - $(’p.first’)
The third option will select all of the <p> tags with the class of “first”. - $(’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. - $(’p[title^="H"]‘)
This enables the selection of all of the <p> tags on the page that have a title that starts with the letter H.
These examples barely scratch the surface.
Almost anything you can do in CSS3 will work in jQuery, plus many more complicated selectors. The complete list of selectors is well documented on the jQuery Selectors documentation page. If you’re feeling super-geeky, you could also read the CSS3 selector specification from the W3C.
Get ready.
$(document).ready()
Traditionally Javascript events were attached to a document using an “onload” attribute in the <body> tag of the page. Forget this practice. Wipe it from your mind.
jQuery provides us with a special utility on the document object, called “ready”, allowing us to execute code ONLY after the DOM has completely finished loading. This is the key to unobtrusive DOM scripting, as it allows us to completely separate our Javascript code from our markup. Using $(document).ready(), we can queue up a series of events and have them execute after the DOM is initialized.
This means that we can create entire effects for our pages without changing the markup for the elements in question.
Hello World! Why $(document).ready() is SO cool
To demonstrate the beauty of this functionality, 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:
Bad markup:
<script language="javascript">
alert('Hello World');
</script>
Good markup:
Using this functionality in jQuery is simple. The following code snippet demonstrates how we might call the age-old “Hello World” alert box after our document has loaded. The true beauty of this markup is that it lives in an external Javascript file. There is NO impact on the (X)HTML page.
$(document).ready(function()
{
alert('Hello World');
});
How it works
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
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.
Bad markup:
HTML:
<h2>This is a heading</h2>
<p class="hide-me-first">
This is some information about the heading.
</p>
CSS:
p.hide-me-first
{
display: none;
}
Assuming that a paragraph with the class of “hide-me-first” is going to first be hidden by CSS and then be displayed by a Javascript after some future user interaction, if the Javascript never runs the content will never be visible.
Good markup:
HTML:
<h2>This is a heading</h2>
<p class="hide-me-first">
This is some information about the heading.
</p>
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 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
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:
- Why unobtrusive DOM scripting is so important for accessibility,
- Why jQuery is the natural choice to implement unobtrusive DOM scripting effects,
- How jQuery selectors work,
- How to implement unobtrusive CSS rules in jQuery.
5. Further Reading
Further Reading: jQuery and JavaScript Practices
- jQuery Web Site: How jQuery Works and Tutorials
John Resig + Other Contributors
One of jQuery’s true strengths is the documentation provided by John Resig and his team. - 51 Best jQuery Tutorials and Examples
- Easy As Pie: Unobtrusive JavaScript
- Seven Rules of Unobtrusive JavaScript
- Learning jQuery
- Visual jQuery
- jQuery Tutorials For Designers
- jQuery For Designers
jQuery for Designers: learn how easy it is to apply web interaction using jQuery. - 15 Days Of jQuery
jQuery tutorials and example code that takes you from zero to hero in no time flat. - 15 Resources To Get You Started With jQuery From Scratch
- The Seven Rules Of Pragmatic Progressive Enhancement
- The Behaviour Layer Slides
Jeremy Keith
Great slide notes giving a quick rundown on unobtrusive Javascripting. - A List Apart: Behavioral Separation
Jeremy Keith
A more in-depth explanation of the idea of separating Javascript into an unobtrusive “behavioural” layer. - Unobtrusive JavaScript with jQuery
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
- Wikipedia: Definition of Semantics
It’s worth understanding the idea of semantics in general prior to trying to wrap one’s head around the concept of semantic markup. - Who cares about semantic markup?
Dave Shea
Dave Shea explores the benefits of semantic markup and - Standards don’t necessarily have anything to do with being semantically correct
Jason Kottke
Kottke discusses the differences between standards compliance and semantic markup. - CSS3 selector specification
W3C
The complete specification for CSS3 selectors (most of which work perfectly in jQuery selectors also). This is great reading for anyone who likes to keep up to date with best practices and standards compliance.
About the author
Alex Holt is a professional interactive designer and web developer who has worked successfully for a variety of clients in Australia, UK, USA and most recently Spain. His blog can be found at: soyrex.com, where he writes sporadically about a wide range of design and development topics (as well as the occasional off-topic rant).


Jon Hughes (September 16th, 2008, 9:27 am)
Very informative article. Great examples, thorough and easy to read!
p.s. Thanks for the plug!
- Jon Hughes
Notes from Phazm
phazm.com/notes
omkar konda (September 16th, 2008, 9:27 am)
Great Post as usual.
Stephanie (September 16th, 2008, 9:49 am)
yesss I love jquery
Benni (September 16th, 2008, 10:12 am)
I just started to work with jQuery and this article is really useful for me. Thanks :-)
Pascal (September 16th, 2008, 10:16 am)
nice work!
Josso (September 16th, 2008, 10:18 am)
Great review of why jQuery is worth using. :)
Brandon (September 16th, 2008, 10:32 am)
Awesome - I’ve been curious/intimidated by jQuery for a while, but this definitely casts it in a more approachable light. Thanks for the quick rundown… you’ve made it pretty clear why I should be picking this up. Great followup set of resources as well - excellent post. Link [www.makedesignnotwar.com]
Paul Gendek (September 16th, 2008, 10:45 am)
jQuery!!!
Paul (September 16th, 2008, 10:52 am)
Great article!
(btw what is being used to display the code? )
Sudirman (September 16th, 2008, 10:56 am)
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
3n1gm4 (September 16th, 2008, 11:00 am)
quite a good article.
just to let you know, the code snippets are showing up twice for each one.
Peter B (September 16th, 2008, 11:01 am)
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.
Link [www.trumpetgroup.com]
Seth (September 16th, 2008, 11:06 am)
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
zero0x (September 16th, 2008, 11:07 am)
woow very nice article :) thank you
Andre (September 16th, 2008, 11:11 am)
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.
nicerobot (September 16th, 2008, 11:16 am)
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.
Han (September 16th, 2008, 11:17 am)
@Paul: Link [www.dreamprojections.com]
Great article! I was waiting for this post ;-)
victor (September 16th, 2008, 11:38 am)
Whats the diference betwen using:
jQuery.cssRule("p.hide-me-first", "display", "none");
instead of :
$("p.hide-me-first").hide();
Peter Mularien (September 16th, 2008, 11:44 am)
Thanks for the article, I’ll bookmark it for future use by jQuery newbies.
@Paul
I believe they’re using the Link [code.google.com] project.
Jose Espinal (September 16th, 2008, 11:47 am)
This post was incredibly well structured.
Thanks for the informative article.
web veteran (September 16th, 2008, 11:58 am)
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
Sean McCambridge (September 16th, 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.
bruno byington (September 16th, 2008, 12:45 pm)
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
Daniel (September 16th, 2008, 12:49 pm)
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.
Siah (September 16th, 2008, 12:56 pm)
very good article.
Thank you.
bruno byington (September 16th, 2008, 1:02 pm)
@ 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
Sylvia (September 16th, 2008, 1:03 pm)
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 ;)
2expertsdesign.com (September 16th, 2008, 1:14 pm)
great info
Fabio Marchi (September 16th, 2008, 1:16 pm)
Hummm…i losted a little time to find the “7 errors game”…heheheh
Jason (September 16th, 2008, 1:22 pm)
@ Paul
Link [code.google.com]
bruno byington (September 16th, 2008, 1:30 pm)
@ Sylvia, nah you arnt drunk, I see the double code snippets too. he he…
Marin (September 16th, 2008, 1:34 pm)
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…
CHelmertz (September 16th, 2008, 1:46 pm)
Is there a reason for some of the code being written out identically more than once?
Jeffrey (September 16th, 2008, 2:07 pm)
Awesome post.. as usual
wael (September 16th, 2008, 2:24 pm)
yeah i did a huge job with J query with some jquerry plugins to manage a real estate web site
check
Link [www.realitalia.co.uk]
i used it to manage projects and unit its great for galleries and show rooms
i used to use Mootools to which is a very good library
but I prefer Jquerry
Link [www.webdesign4me.com]
Alexander Schakel (September 16th, 2008, 2:39 pm)
Super! Great article, keep it going!
dragoshell (September 16th, 2008, 3:15 pm)
Wow.. you guys are great! Superb article! very very useful! Thank you!
Aaron (September 16th, 2008, 4:02 pm)
Jquery is going to be built into my new CMS system which already uses smarty PHP and my new css lib addition.
Link [www.stageguy.co.uk]
Troy (September 16th, 2008, 4:02 pm)
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 :)
archknight79 (September 16th, 2008, 4:40 pm)
jquery really rocks! Thanks guys for the tips :)
Gath (September 16th, 2008, 4:56 pm)
There is a cool comparison of the different js frameworks here:
Link [mootools.net]
edouard duplessis (September 16th, 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
Herdy (September 16th, 2008, 5:24 pm)
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…
Sam (September 16th, 2008, 5:48 pm)
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
神采飞扬 (September 16th, 2008, 6:15 pm)
this is very very perfect!!
Adam McHugh (September 16th, 2008, 6:19 pm)
This is why I love jQuery! It has effectively sped up my Javascript development for client websites and almost guaranteed that stuff will work in all the major browsers!
Link [www.adammchugh.com]
Karl Swedberg (September 16th, 2008, 6:51 pm)
@SamLink [], 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’).
ThemeLib.com (September 16th, 2008, 7:02 pm)
Awesome!
How about Prototype, Mootools, Dojo, … ?
bjornredemption (September 16th, 2008, 8:42 pm)
@victor
the first hides the element instantly while the second fades it out gradually
Sam (September 16th, 2008, 8:50 pm)
Yeah, great article! I have to learn JS soon, so this will help me for sure.. :)))
ahnShev (September 16th, 2008, 8:52 pm)
Great.
ashvin (September 16th, 2008, 9:44 pm)
Smashing JQuery!
Armin Cifuentes (September 16th, 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?
Nakiloe (September 16th, 2008, 11:22 pm)
Very useful, thanks! ^^
eddie (September 16th, 2008, 11:36 pm)
this is a really SM artical
Karthik (September 16th, 2008, 11:40 pm)
Nice Articile , Thanks Lot
Johan de Jong (September 16th, 2008, 11:41 pm)
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.
Rafal (September 16th, 2008, 11:43 pm)
Good article. I use jQuery for a while. Some of the directions will be useful for me.
John (September 17th, 2008, 12:09 am)
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 Link [developer.yahoo.net] of Yahoo’s “Best Practices for Speeding Up Your Web Site” series.
Craig (September 17th, 2008, 12:16 am)
Just to point out something: this assertion is, in fact, not optimal usage of JavaScript:
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.
V1 (September 17th, 2008, 12:17 am)
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.
Primas (September 17th, 2008, 12:20 am)
WOW, very helpful. Thanks a lot.
Greetings from Austria.
Stefan
Sarbjit Singh (September 17th, 2008, 12:37 am)
Amazing!! will get started with JQuery today!!
STPo (September 17th, 2008, 12:46 am)
@Craig > you’re right, JS should be included at the bottom of the document because scripts in
headfreeze the document until they’re completely loaded… which can be pretty long when a whole library is included !patrick h. lauke (September 17th, 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.
Sebastian (September 17th, 2008, 12:55 am)
@V1
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.
Natrium (September 17th, 2008, 1:21 am)
JQuery is yummy!
De Sink (September 17th, 2008, 1:25 am)
Nice Article , Thanks SM
Link [www.desink.com]
Stevie K (September 17th, 2008, 1:41 am)
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.
h-a-r-v (September 17th, 2008, 1:45 am)
Mootools. ;-)
Gonelf (September 17th, 2008, 2:00 am)
i hate mootools
Movie Octopus rules
Mukesh (September 17th, 2008, 2:03 am)
Excellent….very helpfule for coming up developer……..
gr8
Link [www.xhtml-conversion.in]
Lukas Berns (September 17th, 2008, 2:28 am)
One typo…
$(’p[title^=^"H"]‘)should be
$(’p[title^="H"]‘)under Understanding Selectors: the Backbone of jQuery
(not in the <code> block, but in the explanation)
I love jQuery
V1 (September 17th, 2008, 2:45 am)
@Sebastian
Hook me up with a blog. And ill give u 25 reasons to consider when choosing a framework. That matches your project. And also reasons why NOT to use a framework.
@Gath, That only shows the speed of the selectors thats only a small part of the jQuery lib. Did u read this yet.. Link [alex.dojotoolkit.org]
Mиглен (September 17th, 2008, 3:03 am)
Great article!
Roland (September 17th, 2008, 4:38 am)
“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″?
Jon (September 17th, 2008, 4:50 am)
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.
Cheers
Michael Thompson (September 17th, 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!’);
Karl Swedberg (September 17th, 2008, 5:57 am)
@Jon,
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 Link [groups.google.com].
Mig (September 17th, 2008, 6:15 am)
u can check my script on Link []
runa (September 17th, 2008, 7:40 am)
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.
Bleyder (September 17th, 2008, 7:53 am)
Moooooooooootools!!!
Juan Pablo Barrientos Lagos (September 17th, 2008, 7:53 am)
Rlly great article. Thx u.
Regards!
Davin (September 17th, 2008, 8:28 am)
Maybe the non-javscript user enjoys missing out on the web, never mind the welcome message. :D
Alex Holt (September 17th, 2008, 8:55 am)
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)
Not at all. That’s the whole point behind the concept of separating the behavioural layer from presentation etc.
Actually, there are plenty of corporate environments that have blanket javascript-less environments..
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 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)
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)
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 the possible exception of code readability, you’re quite right.
@V1 (#61)
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
De Sink (September 17th, 2008, 9:04 am)
Thanks for the comments Alex Holt.
long but really good.
lawoman (September 17th, 2008, 9:14 am)
Thanks for making it much easier to understand how javascript best be used!
nicerobot (September 17th, 2008, 10:39 am)
Thanks for the response Alex.
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?
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.
michaelaustinproductions.com (September 17th, 2008, 11:01 am)
That is a great help. Thanks a lot. I love j query
Dave (September 17th, 2008, 1:00 pm)
For rule #3, how would you pass additional arguments to your function call?
bruno byington (September 17th, 2008, 1:11 pm)
@ 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 ;)
cheers
bruno
Alex Holt (September 17th, 2008, 1:19 pm)
@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?
Bhargav (September 17th, 2008, 4:11 pm)
Its a very useful post for an upcoming JQuery Developer.
Thank you for posting such beautiful articles.
Brian Reindel (September 17th, 2008, 5:19 pm)
@Jon
A lot of developers get caught up on that one. The way to accomplish this with jQuery is as follows:
$("#myElement").onmousedown(function(){
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:
$(document).ready(function(){
// some code here...
});
When you have the following shortcut:
$(function(){
// 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:
$(function(){
// some code here...
});
and then have this further down in the document:
$(function(){
// some more code here...
});
Both will be called when the DOM is ready.
deniar (September 17th, 2008, 6:48 pm)
Wow, it’s interesting. I never think like this before. Thanks anyway
shakes (September 17th, 2008, 7:15 pm)
great article but the jquery site is just not working….
Duc Ban (September 17th, 2008, 8:21 pm)
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?
Ban.
Ross Bruniges (September 17th, 2008, 9:02 pm)
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…
cam (September 17th, 2008, 10:46 pm)
this site has javascript errors… interesting.
Dileep (September 17th, 2008, 10:54 pm)
Thanks for the post, it really made me realize that jQuery is not that difficult to learn.
neps (September 18th, 2008, 2:26 am)
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!
Alan (September 18th, 2008, 4:27 am)
@Ban
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.
Ryan (September 18th, 2008, 7:11 am)
Great article! Very informative.
Jim (September 18th, 2008, 8:13 am)
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.
Alex Holt (September 18th, 2008, 8:42 am)
@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.
Russell Heimlich (September 18th, 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:
CSS:
.selected { ... whatever styles you want to put here in the stylesheet ... }jQuery:
$('p.hide-me-first').addClass('selected');Mixing in presentation (CSS) and behavior (JavaScript) is just a