Smashing Magazine - we smash you with the information that will make your life easier. really.
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 HSo, 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.
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).
- 238 Comments
- 1
- 2September 16th, 2008 9:27 am
Great Post as usual.
- 3September 16th, 2008 9:49 am
yesss I love jquery
- 4September 16th, 2008 10:12 am
I just started to work with jQuery and this article is really useful for me. Thanks :-)
- 5September 16th, 2008 10:16 am
nice work!
- 6September 16th, 2008 10:18 am
Great review of why jQuery is worth using. :)
- 7September 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. MakeDesign,NotWar
- 8September 16th, 2008 10:45 am
jQuery!!!
- 9September 16th, 2008 10:52 am
Great article!
(btw what is being used to display the code? )
- 10September 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
- 11September 16th, 2008 11:00 am
quite a good article.
just to let you know, the code snippets are showing up twice for each one.
- 12September 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.
- 13September 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
- 14September 16th, 2008 11:07 am
woow very nice article :) thank you
- 15September 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.
- 16September 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.
- 17September 16th, 2008 11:17 am
@Paul: http://www.dreamprojections.com/syntaxhighlighter/?ref=about
Great article! I was waiting for this post ;-)
- 18September 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();
- 19September 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 SyntaxHighligher project. - 20September 16th, 2008 11:47 am
This post was incredibly well structured.
Thanks for the informative article.
- 21September 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
- 22September 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.
- 23September 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
- 24September 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.
- 25September 16th, 2008 12:56 pm
very good article.
Thank you. - 26September 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
- 27September 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 ;)
- 28September 16th, 2008 1:14 pm
great info
- 29September 16th, 2008 1:16 pm
Hummm…i losted a little time to find the “7 errors game”…heheheh
- 30
- 31September 16th, 2008 1:30 pm
@ Sylvia, nah you arnt drunk, I see the double code snippets too. he he…
- 32September 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… - 33September 16th, 2008 1:46 pm
Is there a reason for some of the code being written out identically more than once?
- 34September 16th, 2008 2:07 pm
Awesome post.. as usual
- 35September 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
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 - 36September 16th, 2008 2:39 pm
Super! Great article, keep it going!
- 37September 16th, 2008 3:15 pm
Wow.. you guys are great! Superb article! very very useful! Thank you!
- 38September 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.
come over and have a look - 39September 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 cssThis 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 :)
- 40September 16th, 2008 4:40 pm
jquery really rocks! Thanks guys for the tips :)
- 41September 16th, 2008 4:56 pm
There is a cool comparison of the different js frameworks here:
frameworks comparison - 42September 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
- 43September 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…
- 44September 16th, 2008 5:48 pm
$(’#mydiv’)
The second option will select every <div> that has the id attribute set to mydiv.since it’s an id, there should only be one on the page, so saying “every <div>” is silly. Further, its its not even <div>’s , just the single element that has mydiv as its id (regardless of if that element is a <div> )
Other than that, great article
- 45September 16th, 2008 6:15 pm
this is very very perfect!!
- 46September 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!
- 47September 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’).
- 48September 16th, 2008 7:02 pm
Awesome!
How about Prototype, Mootools, Dojo, … ?
- 49September 16th, 2008 8:42 pm
@victor
the first hides the element instantly while the second fades it out gradually - 50September 16th, 2008 8:50 pm
Yeah, great article! I have to learn JS soon, so this will help me for sure.. :)))
- 51September 16th, 2008 8:52 pm
Great.
- 52September 16th, 2008 9:44 pm
Smashing JQuery!
- 53September 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?
- 54September 16th, 2008 11:22 pm
Very useful, thanks! ^^
- 55September 16th, 2008 11:36 pm
this is a really SM artical
- 56September 16th, 2008 11:40 pm
Nice Articile , Thanks Lot
- 57September 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. - 58September 16th, 2008 11:43 pm
Good article. I use jQuery for a while. Some of the directions will be useful for me.
- 59September 17th, 2008 12:09 am
“All Javascript behaviours should be included in external script files and linked to the document with a <script> tag in the head of the page.”
When you’re using unobtrusive scripting, you can safely move all your scripts to the bottom of the page, to greatly improve performance through progressive rendering and download parallelization.
See this section of Yahoo’s “Best Practices for Speeding Up Your Web Site” series.
- 60September 17th, 2008 12:16 am
Just to point out something: this assertion is, in fact, not optimal usage of JavaScript:
All Javascript behaviours should be included in external script files and linked to the document with a <script> tag in the head of the page.
Reason being: JavaScript should be in external files, yes, but they should not be included in the head of a document, because it actually slows down the loading of a page. Optimal usage would be to include the JavaScript file at the very bottom of the document as the last element. This is not always possible due to scope, but it is highly recommended.
- 61September 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.
- 62September 17th, 2008 12:20 am
WOW, very helpful. Thanks a lot.
Greetings from Austria.Stefan
- 63September 17th, 2008 12:37 am
Amazing!! will get started with JQuery today!!
- 64September 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 ! - 65September 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.
- 66September 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.
- 67September 17th, 2008 1:21 am
JQuery is yummy!
- 68
- 69September 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.
- 70September 17th, 2008 1:45 am
Mootools. ;-)
- 71September 17th, 2008 2:00 am
i hate mootools
Movie Octopus rules
- 72
- 73September 17th, 2008 2:28 am
One typo…
$(’p[title^=^"H"]‘)
should be
$(’p[title^="H"]‘)
underUnderstanding Selectors: the Backbone of jQuery
(not in the <code> block, but in the explanation)I love jQuery
- 74September 17th, 2008 2:45 am
@Sebastian
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.
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/
- 75September 17th, 2008 3:03 am
Great article!
- 76September 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″?
- 77September 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
- 78September 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!');
- 79September 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. - 80
- 81September 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.
- 82September 17th, 2008 7:53 am
Moooooooooootools!!!
- 83September 17th, 2008 7:53 am
Rlly great article. Thx u.
Regards! - 84September 17th, 2008 8:28 am
The non-Javascript user is missing out on our welcome message.”
Maybe the non-javscript user enjoys missing out on the web, never mind the welcome message. :D
- 85September 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)
It seems strange to me that you mention a few times about never depending on javascript in an article about a javascript dependent package.
Not at all. That’s the whole point behind the concept of separating the behavioural layer from presentation etc.
Yes, it’s important to design your webapp to behave properly in a javascript-less environment but to say to NEVER depend on it a little extreme in this age.
Actually, there are plenty of corporate environments that have blanket javascript-less environments..
There are simply webapps that can not be implemented as markup. Games for example.
Games are unlikely to fit into the realm of requiring accessible content. Obviously, yes, there are situations where the theories i’ve outlined will be too restrictive, however for web sites (in the traditional sense) – i would still argue that the “never” depend on javascript rule holds true. You’ve used the word webapp a couple of times, and a web app is a slightly different use case to a website i suppose.
@web veteran (#17)
I think article is hogwash.. its written by someone who has obviously worked in just a handful of best case scenarios. in this real world, u wouldnt go far boy.. fuck offf
I almost didn’t bother replying to your “comment”. If you have nothing constructive to offer.. bite your tongue. Of course if you DO have a point, feel free to express it… I’d love to hear what you have to say… if the assumptions you’ve made in your comment are anything to go by, it should be entertaining to see you try and actually formulate a sound argument.
@Sean McCambridge (#18)
Good intro to jQuery for beginners. Though I’m not sure the author has it right in his $(’document’).ready() explanation. The good/bad thing there just doesn’t make sense. I love jQuery, but the great thing about it is you can still mix in naked JavaScript when you need to. Writing JS from scratch is still fine. So it’s misleading and vague to say you absolutely should put an alert() under document ready.
Writing JS from scratch IS still fine, however whenever there is a choice between writing our own code and using a framework method to achieve a goal, I would argue that we should use the framework (which is already tested across multiple browser implementations etc..)… why reinvent the wheel?
But to answer your question, in the case of an alert, it doesn’t need to be in the document.ready, the point i was trying to illustrate was HOW document.ready works (without scaring beginners of with a complicated code example)..
@Marin (#28)
Rule #5 seems to me like SEO hacking. If something needs to be hidden, by default, I would prefer the CSS solution (since Google sort of understand css but not JS). I’m wondering why someone would put extra code for something that will be hidden
Marin, i think you missed the point. The reason why the CSS solution is bad is that it will work even if Javascript is disabled, which leaves the Javascript-less user without access to that content. Moving the hiding implementation into Javascript is the key to degrading gracefully…
@Michael Thompson (#77)
With jQuery’s chaining, there’s no need to set something as a variable and then manipulate it.
With the possible exception of code readability, you’re quite right.
@V1 (#61)
Really, name something, i dare u give us a VALID reason. What makes jquery special and better than the rest of librarys. This post is more about advertising jQuery and shows only stuff that other librarys can do to.
Valid reason: I LIKE Jquery, I also USE Jquery. I dare you to give us a VALID reason WHY NOT Jquery.
@Stevie K (#69)
Agreed. Learning JS IS definitely a benefit. It wasn’t my intention to suggest that RAW Javascript is bad, however if you’re - 86September 17th, 2008 9:04 am
Thanks for the comments Alex Holt.
long but really good. - 87September 17th, 2008 9:14 am
Thanks for making it much easier to understand how javascript best be used!
- 88September 17th, 2008 10:39 am
Thanks for the response Alex.
That’s the whole point behind the concept of separating the behavioral layer from presentation
Right, this separation is probably always preferred. But to say “never depend on javascript” is too heavy handed. It should be up to the designer to decide whether it should or shouldn’t be a requirement. I think you’re examples nicely show ways to approach it but “never”, it just too absolute for me.
Also, no mention of the noscript tag?
… for web sites (in the traditional sense)
To support interactive and robust usability features currently requires programming. If we ever have a standard markup for data bindings and validation, it’ll go a long way towards removing that dependency but i don’t think that’s even on the horizon.
It really just boils down to there being many models for site design between content delivery (traditional) and fully interactive (programming). If the content is not interesting or important without the interactivity, i’d choose to require javascript.
- 89September 17th, 2008 11:01 am
That is a great help. Thanks a lot. I love j query
- 90September 17th, 2008 1:00 pm
For rule #3, how would you pass additional arguments to your function call?
- 91September 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
- 92September 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?
- 93September 17th, 2008 4:11 pm
Its a very useful post for an upcoming JQuery Developer.
Thank you for posting such beautiful articles. - 94September 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.
- 95September 17th, 2008 6:48 pm
Wow, it’s interesting. I never think like this before. Thanks anyway
- 96September 17th, 2008 7:15 pm
great article but the jquery site is just not working….
- 97September 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.
- 98September 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…
- 99September 17th, 2008 10:46 pm
this site has javascript errors… interesting.
- 100September 17th, 2008 10:54 pm
Thanks for the post, it really made me realize that jQuery is not that difficult to learn.
- 101September 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!
- 102September 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. - 103September 18th, 2008 7:11 am
Great article! Very informative.
- 104September 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.
- 105September 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.
- 106September 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 as big of a no no as using a table in place of a definition list (DL). See Rule #3 above!
- 107September 18th, 2008 11:36 am
@Daniel
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.
Framework (times in ms) Mootools 1.2: 143, 137, 136, 141, 151 jQuery 1.2.6: 141, 140, 144, 146, 142 Prototype 1.0.6.2: 282, 284, 279, 277, 276 YUI 2.5.2(beta): 429, 437, 437, 437, 425 Dojo 1.1.1: 140, 155, 149, 151, 151
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:…the $ symbol is also set up as a shortcut for jQuery. Thankfully, this is done in a non-destructive way: if you need your old $ function back (if you are already using code based on Prototype, for example) you can call jQuery.noConflict() to revert to the old $ function.
(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.Copyright (c) 2008 John Resig, http://jquery.com/
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
“Software”), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software. - 108September 18th, 2008 11:45 am
Oops – forgot to mention you should check out jQuery’s discussion group for support, it’s got tons of people who are nice, knowledgeable, and willing to help.
- 109September 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.
- 110September 18th, 2008 6:26 pm
To add on to Alex C.’s argument, I think jQuery is a great library to use because of it’s legibility. One of the hardest things about development can be adapting to someone else’s coding style. This can be especially difficult with JavaScript because it is a loosely typed language.
I’ve found that jQuery makes JavaScript much more understandable, and hopefully this will help future developers who work with my code.
Kevin Leary
kevinleary.net - 111September 19th, 2008 8:54 am
very informative, good job as usual!
- 112September 19th, 2008 11:50 pm
Sometimes the Separate Javascript Functionality doesnt work, you need to add onclick when you are printing a html/javascript code via ajax, for example when your reload a chunk of html code with javascript and events inside, you must use onclick otherwise jQuery will no work.
- 113September 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.
- 114September 20th, 2008 2:38 am
I use mootools AND Jquery. With this I get the best from both worlds and don’t have to choose!
More info on how this is done can be found on
docs.jquery.comI 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.
- 115September 20th, 2008 9:40 am
Excellent! jQuery is a scary thing no more. :)
Thank you! - 116September 21st, 2008 6:32 am
@Roberto
Check out the Live Query Plugin at Link
Kevin Leary
kevinleary.net - 117September 22nd, 2008 6:13 am
Good article but i have to say something…
jQuery is simple and good for beginners of javascripts and little webapps. But in a complicated application, it’s recommanded to keep a hand on all your js. So jQuery could be good but could be a handicap if there’s a compatibility problem. I think as exemple if an item has two or more css classes, if document.onmousemove changes during your page living…
If an ajax request rewrite your innerHTML, does the jQuery reassign bindings between items and js functions…A lot of questions we have to ask before using “free downloadable stuff” for our websites.
- 118September 22nd, 2008 6:35 pm
jQuery sux, I really don’t understand why this shitty library is so popular.. strange API, it’s easy to make mistake in those stupid function chains, fucked up unintuitive documentation and overall quite limited features for 94kb (uncompressed).. in my opinion mooTools is ten times better than jQuery, much more elegant and friendly with clean API
- 119September 22nd, 2008 9:25 pm
Nice and impressive article. Nice examples, simple writing makes easy to understand the features.
thanks to the author.
- 120September 23rd, 2008 3:09 pm
If you do not call the method inline onclick etc, then you have to traverse the DOM to bind it to that link (or div etc) adding overhead. Also for another designer viewing the code, it would be hard to judge if there is a function bound to a particular Dom object by looking at the html.
Also when dealing with a large site, waiting for the document.ready() function to call may take a while, for eg 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. - 121September 23rd, 2008 3:37 pm
I agree with comments 44, 59 and 60.
An ID must be unique within the DOM, so returning every element with a given ID doesn’t make sense. There should be zero or one matching element. - 122September 25th, 2008 3:06 am
Excellent jQuery examples and explanation. Recently I joined new office where they have put a lot of efforts in jQuery and its plugins. Almost everything and anything you can possibly do with jQuery while keeping in mind what we call web standards. Even pretty flash effects can also be made with jQuery. Its time saving and effective and cross browser.
- 123September 29th, 2008 6:00 am
Excellent article. Till date i was stunned on seeing some web2.0 sites with effects and when i check the view source nothing will be there to track. But today only i came to know that trick.
Smashing Magazine Rocks !!!!
- 124September 30th, 2008 9:01 pm
It’s really cool article for JQuery lovers.
Thanks - 125October 3rd, 2008 11:21 am
please add me to the email list
- 126October 4th, 2008 2:14 pm
This article is a good introduction to jQuery.
Instead of using the above mentioned jQuery cssRule plugin we can simply use:$(”element.className”).css({display: “none”});
Corrections are welcome.
Thank you for this article.
enjoy :)
- 127October 6th, 2008 10:40 am
I love jQuery. I have been using it for some time now. It still amazes me that people argue back and forth on javascript frameworks. If you don’t like a certain framework, don’t use it, and if you know the article is about said framework, don’t read it!
Really, it’s like people go out of their way to argue when they could be making a cup of tea or something. =D
- 128November 2nd, 2008 2:20 am
kereen
- 129November 18th, 2008 2:09 am
gr8 ,very easy to understand the basic of jquery
- 130November 21st, 2008 9:36 pm
Worthless (like jQuery.) Same for MooTools and the rest. Browser scripting and general-purpose libraries do not mix. Furthermore, jQuery is some of the worst code I have ever seen (in any context.)
Wow, you can write terrible, incompatible and grossly inefficient code in less lines (typically indecipherable), without actually learning anything (except how to use jQuery.) Certainly your clients will be put off when they start losing leads (due to the incessant browser sniffing), but you will have already cashed your check, right?
Learn the Javascript lanaguage and acquire some experience with browser scripting before you decide to jump in with both feet (with somebody else’s anchor around your neck.)
- 131December 31st, 2008 10:20 am
Nice and impressive article.
thanks to the author. - 132January 2nd, 2009 3:39 am
I have been working in php for last 1.3 yrs. Always wanted to have some effects that look good and should work efficiently. As a plugin jQuery works fine. I m a newbie and trying to get something through the article. Its really good to read. It was a good start for me after going through the article. If any further query could be entertained in personal I would be highly thankful to the author. Any ways its great!!!
- 133January 15th, 2009 9:35 pm
Nice article and easy to understand Jquery
- 134January 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?
- 135January 28th, 2009 10:24 am
great post.
- 136January 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.
- 137January 31st, 2009 3:33 pm
You need to branch away from jQuery for a bit there. You seem very dependent on jQuery which is not good at all. What happens when you are assigned a project and the client, web master, or anyone above you, says you cannot use jQuery. You will truly be lost. This is not a comment to harass you i want to merely encourage you do learn JavaScript. I have one reason why im not a fan of others using jQuery and im starting to see it more and more. People think they know what the hell they’re doing but in reality they don’t.
First off dont create CSS on the fly to be applied to your markup. That is dumb.
you can simply do:
.none {
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. - 138February 11th, 2009 3:39 pm
I beg to differ on #2.
Although this is a great tactic for handling multiple items, I think it may be a bit wasteful when using it on just one link. There were several talks on YUI theatre, showing that the largest amount of time consumed is on DOM manipulation and not the actual javascript. You need to query the DOM each time you need to use that function and then you have to observe all click events and check whether they came from the proper element. So, it may be useful a good amount of the time, but it’s not the catch all.
i consider myself an intermediate programmer, so I may have misquoted or misrepresented something. If I have, please let me know.
Edit: You’re not using any observation for that particular method, so I stand corrected. The thought still holds true for the manipulation of the DOM.
- 139February 15th, 2009 2:04 pm
Totally agree with Mike (comment 137).
- 140February 27th, 2009 1:54 pm
i cannot agree on the standards you are setting up here. rule number 1 is the worst attempt to set up practices ever. You rule: Never include Javascript events as inline attributes. This practice should be completely wiped from your mind. Formulating such a rule has disqualified you to participate in any real world operation that deals with javascript on a professional (real world) level. That rule #1 of yours will work for the one or two examples you are giving, but you don’t even consider stating that this works in these limited cases only – and you fail to inform the audience that there are many cases where inline events are the only way to go. What you do by setting up rules appears to me shows a rather limited approach on programming javascript solutions. This is not bad, and if your javascript is about rollovers or image replacement, or navigations, well yeah, even then your rules do not apply.
Of course:
THIS [a href= "#" rel="nofollow" ]Click![ / a ]
can be replaced by
THAT [a href = "backuplink.html" rel="nofollow " ]Click![ /a ]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.
- 141
- 142March 26th, 2009 2:38 am
Great article!
It’s really helpful, I’ll suggest this page for all of my web-developer friends… - 143April 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?
- 144April 10th, 2009 9:51 am
Nice article but using dt and dl for option lists is not very nice.
There tags are meant to be used for glossaries not for option lists… - 145April 15th, 2009 8:28 am
Great article. Thanks
jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery - 146April 17th, 2009 9:52 am
Really awesome article man.. I Love JQuery….
- 147April 23rd, 2009 12:41 pm
oh God.
I totally LOVE this article. - 148May 18th, 2009 8:55 am
unique article
- 149May 26th, 2009 8:43 pm
YESYES BEST
- 150May 26th, 2009 8:44 pm
Iam best at handball you want beat me?? (NOPE SORRY)
- 151May 26th, 2009 8:46 pm
Yes i am a pretty girl in ACT, Canberra , Australia You want puhnnani??
- 152May 27th, 2009 1:35 pm
Amazing article, thanks!
- 153June 3rd, 2009 11:46 am
This article is rather non-creative as it only describes ementary things done in a more DOM-way. jQuery got to be more than xhtml-strict-fanboys head-quarter.
Appriciate your effort, but for me it’s back to google…
- 154June 16th, 2009 11:30 pm
Can i use this article in my website?
- 155June 25th, 2009 9:29 pm
good post. it really helps me :)
- 156July 6th, 2009 5:35 pm
Just when you take a breath and mumble, “Yeah I got this!” You magazinesmashers remind us tag-a-longs that learning web design is like the horizon, the goal is always just beyond our line of sight. The implications here were not good, they were great!! Thanx for the terra firma.
- 157July 12th, 2009 11:58 am
Excellent if not obvious best practices but not always practical or necessary. The majority of applications are business applications where the client can be stipulated: must use a browser that supports JavaScript and CSS. Creating a pure HTML solution is a colossal waste of time and money. Even for public sites, I have no problem stipulating that you must have CSS and JavaScript. Interweaving support for visually impaired users is equally asinine. Instead, make them a completely separate site geared toward audible navigation and screen reading, rather than pretend you’ve actually done them a favor by adding 508 compliance.
- 158July 27th, 2009 12:31 pm
i built an animated and fast “search in this page” search engine by using the “:contains” selector of jQuery:
mix of js and jquery syntyax:
function search {
var word=document.getElementById(’mysearchbox’).value;
$(”div:contains:(” + word + “)”).show(200);
}css:
div {
display: none
}html:
it contains some bad markup but it works and developable.
- 159August 11th, 2009 11:50 pm
bad and worst .. i never sean such a worst article in my career…..
don’t try to publish this kind of article - 160August 18th, 2009 7:05 am
I am looking for an example of a complete jQuery web project, not just examples to accomplish a specific task, but instead a project demonstrating “best practices” for an entire site using jQuery. Ideas?
- 161August 31st, 2009 2:12 pm
All a bunch of bullshit. You don’t even give reasons for half of your “bad” “good” lists. Just glorified opinions from a script kiddie.
- 162August 31st, 2009 10:15 pm
For using JQuery i suggest to try follow new free PHP IDE
Codelobster PHP Edition with special JQuery plug-in. - 163September 6th, 2009 4:41 am
It was a great Jquery help.
It might useful to me.
Thanks.
__
jquery help - 164September 14th, 2009 1:06 am
Yes, that great JQuery, we can do more effective coding by using JQuery.
- 00
There are no trackbacks at this time. If you are interested in leaving a trackback, please use this URL.
Leave a Comment
Make sure you enter the * required information where indicated. Please also rate the article as it will help us decide future content and posts. Comments are moderated – and rel="nofollow" is in use. Please no link dropping, no keywords or domains as names; do not spam, and do not advertise!
Interact
Popular
- 100 Wordpress Themes
- Photoshop Tutorials
- Fantastic Wallpapers
- 40+ Excellent Freefonts
- Dual-Screen Wallpapers
- Wordpress Themes for 2009
- Illustrator Tutorials
- Incredible Free Icon Sets
- High-Quality Free Fonts
- 30 Scripts For Galleries
- Photoshop Text Effects
- Useful Icon Sets
- Web Design Trends
- iPhone Wallpapers
- Before Launching a Website
- CSS Layouts And Templates
- Photoshop Actions
- Stunning Pictures and Photos
- Fantastic HDR Pictures
- Logo Design Tutorials
- Free Design Templates
- 10 Mistakes In Logo Design
- Photoshop Custom Shapes
- 40 Creative Design Layouts
- 8 Layout Solutions
- 53 CSS Techniques
- Photography Techniques
- Black & White Photography
- Styling Design Elements
- CSS-Based Forms
- 50 jQuery Techniques
- 50 Portfolio Websites
- 50 CSS Techniques
- Creative Logo Designs
- Desktop Wallpapers
- 25 Open Source Mac Apps
- 50 Free Icon Sets
- Apple ad bombing Windows 7 on Google - http://bit.ly/28ctPq
- Atatonic - a fresh CSS framework - http://bit.ly/4oOV2w (via @umutm)
- @HrvojeKC yes, that's an interesting idea. Maybe when the waiting is over, we'll write a detailed post about it.
- @benbeltran thanks, Ben, your support means a lot to us.
- @dandenney thanks for the nice words, Dan - really appreciate it.
- @TheKheiron well, it's not entirely our fault. But we will certainly learn a lot from this horrible experience.

(3 votes, average: 4.33 out of 5)
Very informative article. Great examples, thorough and easy to read!
p.s. Thanks for the plug!
– Jon Hughes
Notes from Phazm
phazm.com/notes