jQuery and JavaScript Coding: Examples and Best Practices

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.







Jon Hughes
September 16th, 2008 9:27 amVery informative article. Great examples, thorough and easy to read!
p.s. Thanks for the plug!
– Jon Hughes
Notes from Phazm
phazm.com/notes
Hussain
June 17th, 2012 5:45 pmJQuery is javascript. The delination between good and terible mark up is not based on a sound understanding of javascript and jquery.
omkar konda
September 16th, 2008 9:27 amGreat Post as usual.
Stephanie
September 16th, 2008 9:49 amyesss I love jquery
Benni
September 16th, 2008 10:12 amI just started to work with jQuery and this article is really useful for me. Thanks :-)
Pascal
September 16th, 2008 10:16 amnice work!
Josso
September 16th, 2008 10:18 amGreat review of why jQuery is worth using. :)
Brandon
September 16th, 2008 10:32 amAwesome – 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. MakeDesign,NotWar
Paul Gendek
September 16th, 2008 10:45 amjQuery!!!
Paul
September 16th, 2008 10:52 amGreat article!
(btw what is being used to display the code? )
Sudirman
September 16th, 2008 10:56 amYes, 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 amquite 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 amAs 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.
Seth
September 16th, 2008 11:06 amI 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 amwoow very nice article :) thank you
Andre
September 16th, 2008 11:11 amGood 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 amNice 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: http://www.dreamprojections.com/syntaxhighlighter/?ref=about
Great article! I was waiting for this post ;-)
victor
September 16th, 2008 11:38 amWhats the diference betwen using:
jQuery.cssRule("p.hide-me-first", "display", "none");
instead of :
$("p.hide-me-first").hide();
phil
September 8th, 2010 5:38 am@victor
As far as i know .hide() adds style=”display:none” to an object.
.cssRule adds a property to the whole class.
Peter Mularien
September 16th, 2008 11:44 amThanks for the article, I’ll bookmark it for future use by jQuery newbies.
@Paul
I believe they’re using the SyntaxHighligher project.
Jose Espinal
September 16th, 2008 11:47 amThis post was incredibly well structured.
Thanks for the informative article.
web veteran
September 16th, 2008 11:58 amI 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 pmHey 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 pmWhy 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 pmvery 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 pmFirst 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 pmgreat info
Fabio Marchi
September 16th, 2008 1:16 pmHummm…i losted a little time to find the “7 errors game”…heheheh
Jason
September 16th, 2008 1:22 pm@ Paul
http://code.google.com/p/syntaxhighlighter/
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 pmgreat 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 pmIs there a reason for some of the code being written out identically more than once?
Jeffrey
September 16th, 2008 2:07 pmAwesome post.. as usual
wael
September 16th, 2008 2:24 pmyeah i did a huge job with J query with some jquerry plugins to manage a real estate web site
check
http://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
http://www.webdesign4me.com
Alexander Schakel
September 16th, 2008 2:39 pmSuper! Great article, keep it going!
dragoshell
September 16th, 2008 3:15 pmWow.. you guys are great! Superb article! very very useful! Thank you!
Aaron
September 16th, 2008 4:02 pmJquery 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
Troy
September 16th, 2008 4:02 pmOn 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 pmjquery really rocks! Thanks guys for the tips :)
Gath
September 16th, 2008 4:56 pmThere is a cool comparison of the different js frameworks here:
frameworks comparison
edouard duplessis
September 16th, 2008 5:11 pmjQuery 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 pmI 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 pmsince 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 pmthis is very very perfect!!
Adam McHugh
September 16th, 2008 6:19 pmThis 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!
Adam McHugh – PHP Developer
Karl Swedberg
September 16th, 2008 6:51 pm@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’).
ThemeLib.com
September 16th, 2008 7:02 pmAwesome!
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 pmYeah, great article! I have to learn JS soon, so this will help me for sure.. :)))
ahnShev
September 16th, 2008 8:52 pmGreat.
ashvin
September 16th, 2008 9:44 pmSmashing JQuery!
Armin Cifuentes
September 16th, 2008 10:20 pmNice 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 pmVery useful, thanks! ^^
eddie
September 16th, 2008 11:36 pmthis is a really SM artical
Karthik
September 16th, 2008 11:40 pmNice Articile , Thanks Lot
Johan de Jong
September 16th, 2008 11:41 pmGreat 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 pmGood article. I use jQuery for a while. Some of the directions will be useful for me.
John
September 17th, 2008 12:09 amWhen 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.
Craig
September 17th, 2008 12:16 amJust 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 amI’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 amWOW, very helpful. Thanks a lot.
Greetings from Austria.
Stefan
Sarbjit Singh
September 17th, 2008 12:37 amAmazing!! 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 amunder “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 amJQuery is yummy!
De Sink
September 17th, 2008 1:25 amNice Article , Thanks SM
Diseño Web 2.0 – De Sink
Stevie K
September 17th, 2008 1:41 amWas 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 amMootools. ;-)
Gonelf
September 17th, 2008 2:00 ami hate mootools
Movie Octopus rules
Mukesh
September 17th, 2008 2:03 amExcellent….very helpfule for coming up developer……..
gr8
XHTML programmer
Lukas Berns
September 17th, 2008 2:28 amOne 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.. http://alex.dojotoolkit.org/2008/08/dojos-query-system-no-really-its-that-fast/
Mиглен
September 17th, 2008 3:03 amGreat 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 amHi 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 amWith 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 jQuery Google Group.
Mig
September 17th, 2008 6:15 amu can check my script on Website done full of jquery and google APIs
runa
September 17th, 2008 7:40 amI 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 amMoooooooooootools!!!
Juan Pablo Barrientos Lagos
September 17th, 2008 7:53 amRlly great article. Thx u.
Regards!
Davin
September 17th, 2008 8:28 amMaybe the non-javscript user enjoys missing out on the web, never mind the welcome message. :D
Alex Holt
September 17th, 2008 8:55 amThanks 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 amThanks for the comments Alex Holt.
long but really good.
lawoman
September 17th, 2008 9:14 amThanks for making it much easier to understand how javascript best be used!
nicerobot
September 17th, 2008 10:39 amThanks 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 amThat is a great help. Thanks a lot. I love j query
Dave
September 17th, 2008 1:00 pmFor 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 pmIts 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 pmWow, it’s interesting. I never think like this before. Thanks anyway
shakes
September 17th, 2008 7:15 pmgreat article but the jquery site is just not working….
Duc Ban
September 17th, 2008 8:21 pmThanks 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 pmI 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 pmthis site has javascript errors… interesting.
Dileep
September 17th, 2008 10:54 pmThanks for the post, it really made me realize that jQuery is not that difficult to learn.
neps
September 18th, 2008 2:26 amRule #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 amGreat article! Very informative.
Jim
September 18th, 2008 8:13 amJQuery 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 amI 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 as big of a no no as using a table in place of a definition list (DL). See Rule #3 above!
Alex Calara
September 18th, 2008 11:36 am@Daniel
I know it’s only 5 runs, but jQuery looks far from the worst performing.
@V1
“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.”
See above. This has some good reasons why you should use jQuery, but my favorite is this one:
(more on using jQuery with other libraries)
If it’s small, quick, does what you need it to, and doesn’t prevent you from using additional javascript frameworks (should you need to), there’s not very many reasons you shouldn’t use jQuery.
@Jim
“Their licensing model is a mess and their ongoing development and support is almost non-existant.”
I don’t know – an MIT license is pretty nice.
Alex Calara
September 18th, 2008 11:45 amOops – 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.
Marin
September 18th, 2008 2:08 pm@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.
Kevin
September 18th, 2008 6:26 pmTo 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
kevinleary.net
Roy V.
September 19th, 2008 8:54 amvery informative, good job as usual!
roberto
September 19th, 2008 11:50 pmSometimes 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.
Alex Holt
September 20th, 2008 12:08 am@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.
danne
September 20th, 2008 2:38 amI 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
docs.jquery.com
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.
bycolor
September 20th, 2008 9:40 amExcellent! jQuery is a scary thing no more. :)
Thank you!
Kevin
September 21st, 2008 6:32 am@Roberto
Check out the Live Query Plugin at Link
Kevin Leary
kevinleary.net
Geck1942
September 22nd, 2008 6:13 amGood 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.
someone
September 22nd, 2008 6:35 pmjQuery 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
M.M.H.Masud
September 22nd, 2008 9:25 pmNice and impressive article. Nice examples, simple writing makes easy to understand the features.
thanks to the author.
Irukandji
September 23rd, 2008 3:09 pmIf 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 amazon.com. 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.
Mike H
September 23rd, 2008 3:37 pmI 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.
javed Khalil
September 25th, 2008 3:06 amExcellent 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.
AnkamSarav
September 29th, 2008 6:00 amExcellent 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 !!!!
Samir Shah
September 30th, 2008 9:01 pmIt’s really cool article for JQuery lovers.
Thanks
Leona Rubin
October 3rd, 2008 11:21 amplease add me to the email list
loveprone
October 4th, 2008 2:14 pmThis 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 :)
Steve
October 6th, 2008 10:40 amI 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
tsauri28
November 2nd, 2008 2:20 amkereen
Amita
November 18th, 2008 2:09 amgr8 ,very easy to understand the basic of jquery
David Mark
November 21st, 2008 9:36 pmWorthless (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.)
Vaibhav Gupta
December 31st, 2008 10:20 amNice and impressive article.
thanks to the author.
pradeep pathak
January 2nd, 2009 3:39 amI 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!!!
Rukhsar Ahmad
January 15th, 2009 9:35 pmNice article and easy to understand Jquery
Alex Holt
January 20th, 2009 6:32 am@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?
Nitin
January 28th, 2009 10:24 amgreat post.
Rozzy
January 30th, 2009 7:49 pm@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.
Mike
January 31st, 2009 3:33 pmYou 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 {
display: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:
$(“#myElement”).click(function(){
//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) {
window.open( 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.
John
February 11th, 2009 3:39 pmI 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.
guest
February 15th, 2009 2:04 pmTotally agree with Mike (comment 137).
ray
February 27th, 2009 1:54 pmi 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 ]
But:
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.
Jeremy
March 13th, 2009 8:06 pmjquery rocks!!
http://www.bathrobewarrior.com
Robert
March 26th, 2009 2:38 amGreat article!
It’s really helpful, I’ll suggest this page for all of my web-developer friends…
David Mark
April 7th, 2009 12:36 pm“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?
Manuel
April 10th, 2009 9:51 amNice 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…
viralpatel
April 15th, 2009 8:28 amGreat article. Thanks
jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery
Ibrahim
April 17th, 2009 9:52 amReally awesome article man.. I Love JQuery….
joão
April 23rd, 2009 12:41 pmoh God.
I totally LOVE this article.
emoracket
May 18th, 2009 8:55 amunique article
Phillip
May 26th, 2009 8:43 pmYESYES BEST
Phillip Matthew
May 26th, 2009 8:44 pmIam best at handball you want beat me?? (NOPE SORRY)
Phillip Matthew
May 26th, 2009 8:46 pmYes i am a pretty girl in ACT, Canberra , Australia You want puhnnani??
Alfred
May 27th, 2009 1:35 pmAmazing article, thanks!
fundamentalists...
June 3rd, 2009 11:46 amThis 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…
Sekar
June 16th, 2009 11:30 pmCan i use this article in my website?
kiseok
June 25th, 2009 9:29 pmgood post. it really helps me :)
doktorthomas
July 6th, 2009 5:35 pmJust 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.
Rick O'shay
July 12th, 2009 11:58 amExcellent 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.
W3
July 27th, 2009 12:31 pmi 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);
}
css:
div {
display: none
}
html:
it contains some bad markup but it works and developable.
Arunkumar
August 11th, 2009 11:50 pmbad and worst .. i never sean such a worst article in my career…..
don’t try to publish this kind of article
Kevin
August 18th, 2009 7:05 amI 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?
Lee
August 31st, 2009 2:12 pmAll a bunch of bullshit. You don’t even give reasons for half of your “bad” “good” lists. Just glorified opinions from a script kiddie.
Stas
August 31st, 2009 10:15 pmFor using JQuery i suggest to try follow new free PHP IDE
Codelobster PHP Edition with special JQuery plug-in.
Salsan Jose E
September 6th, 2009 4:41 amIt was a great Jquery help.
It might useful to me.
Thanks.
__
jquery help
shariq
September 14th, 2009 1:06 amYes, that great JQuery, we can do more effective coding by using JQuery.
indialike.com
December 15th, 2009 11:45 pmVery nice and useful tutorials to web designers,
Thanks for posting.
shen
December 23rd, 2009 6:30 pmFrom 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.
Julio
February 21st, 2010 10:14 amYour article rocks! I wish every article which talked about Jquery an JavaScript were like this…
Thanks a lot.
Eric
February 22nd, 2010 3:08 amObviously, the syntax
jQuery.cssRule(“p.hide-me-first”, “display”, “none”);
is more complex to understand for a javascript programmer than
obj.style.display=’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.
Alex Holt
May 3rd, 2010 8:52 amEric: The difference is, my code rewrites the rule in the stylesheet, yours alters the style on an object.
mohan
April 18th, 2010 10:45 pmVery good articles for the newbie !!!!!!
Mark
April 23rd, 2010 11:19 amSo you want to replace:
<a href=”#” onclick=”doSomething()”>Link!</a>
With:
<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.
arslan
June 12th, 2010 10:22 amyes i love jQuery , i am still learning this particular stuff but i would suggest that this would be a great alternative to JavaScript coding .
php customization
June 21st, 2010 10:52 pmHi..,
This article is using to clarify my client doubts.
This is is nice script.. Its help to improve the beginner knowledge..
Thanks:-)
Salsan Jose
June 22nd, 2010 4:39 pmI liked your simplicity of JQuery presentation. It would be great if you can write about Javascript Prototype framework best practices .
Thanks,
Salsan Jose
Harpreet
July 31st, 2010 9:32 pmThanks for the post.
will try to improve
wrote something about start date end date datepicker and datatable some time back
http://rowsandcolumns.blogspot.com/2010/07/jquery-start-dateend-date-datepicker.html
Mike
August 28th, 2010 4:37 am“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.
Himanshu
January 4th, 2011 5:22 pmI 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.
Eschi
October 30th, 2010 2:48 amGreat 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?!
Himanshu
January 4th, 2011 5:18 pmThanks 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.
Cheers!
Priya
February 2nd, 2011 1:46 amJquery is really having great dom scripting capabilities, i had experienced.
Priya
February 2nd, 2011 1:48 amHi priya you told is true
bcmoney
February 10th, 2011 10:41 amVery 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:
http://www.devinrolsen.com/css-hide-and-display-content/
http://www.tjkdesign.com/articles/dropdown/demo.asp
http://devsnippets.com/article/techniques-using-pure-css-only.html
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!
kiran hirade
February 11th, 2011 2:33 amthanks it is great article …………
kiran hirade
February 11th, 2011 2:34 amthanks it is great article ………..very important ………….
Raheel
February 21st, 2011 8:46 pmNice script…..
muhammad taahaa
March 3rd, 2011 12:35 amvery good work………..taahaa….
jmilloy
March 31st, 2011 11:13 amThis 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.
Kiran Kilari
April 7th, 2011 11:27 pmVery useful for the learners…
mikiyfi
April 13th, 2011 8:19 pmIt’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.
Daniel
April 30th, 2011 3:55 amIn 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.
Dave
May 26th, 2011 4:26 amgreat guide for a jQuery noob like myself.
thanks!
Marvin
May 31st, 2011 8:31 amNice 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 form.how 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 ()
{
$(‘#employeeInfoForm’).submit(function()
{
var postForm = true;
$(‘:input’).each(function(index)
{
if ( $(this).val() == “” )
{
if ($(this).attr(“id”)!=”EmailAddress”)
{
$(‘#validatortxt_’ + (index + 1).toString()).text(” *”);
}
postForm = false;
}
else
{
$(‘#validatortxt_’ + (index + 1).toString()).text(“”);
postForm = true;
}
});
return postForm;
});
};
//form
</form
siva shankar
June 2nd, 2011 9:35 amThanks for giving this data
phoenix
August 24th, 2011 12:54 amIn 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.
Maxwell
October 26th, 2011 12:35 amThanks 4 diz.
Bhupendra Singh
November 25th, 2011 5:44 amThis is one of the best answer so far, I have read online. No crap, just useful information. Very well presented. I had found another good collection of JQuery interview question and answer over internet. please check out this link…
mindstick.com/Interview/367/Why%20is%20JQuery%20better%20than%20javascript
Vladimir
November 30th, 2011 7:15 am$(‘#mydiv’)
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.
Moacir
June 14th, 2012 11:50 amVery good article! Thank you!
Hussain
June 17th, 2012 5:51 pmTo 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.
Muhammad Hussain Wazir
July 4th, 2012 10:11 pmThis is really help full topic and really enjoy and learn from this.
Thanks To all for such informational topic sharing.
Stephani Djojo
July 16th, 2012 6:28 amawesome article!! Good coding, good decumentation, good programmer!!!
JTf
January 4th, 2013 2:21 pmWhat 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.
first
January 10th, 2013 10:32 pmHere are some points regarding jQuery best practice…. firstemission.blogspot.in/2013/01/best-practice-with-jquery.html
Chat Leaky
February 9th, 2013 7:16 pmHere is yet another great tool for JavaScript and jQuery developers.
http://www.dofactory.com/framework/javascript-jquery-patterns.aspx.
I have found it very helpful.
igi ladera
March 8th, 2013 12:20 amThis article is AWESOME!!! I never thought there is cssRule. What a GREAT post!!!
simpal chaudhary
March 25th, 2013 11:23 pmNice article…!!!
Alex Leblois
June 12th, 2013 3:09 amThis is awesome!! really helpful for me. Thanks for sharing with us. Following links also helped me to complete my task.
http://www.mindstick.com/Articles/22cd0cd6-caf7-495e-a06e-70fdd000f1bb/?Simple%20Javascript%20Practice%20Shopping%20Cart
http://www.codeproject.com/Articles/580165/JavaScript-Best-Practices