jQuery and JavaScript Coding: Examples and Best Practices

Advertisement

Things to do today..

When used correctly, jQuery21 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?

jQuery21 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:

CrossBad markup:

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

<a onclick="doSomething()" href="#">Click!</a>
TickGood 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 jQuery3 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.

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

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

CrossTerrible 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>
CrossBad 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>
TickGood 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 later5.

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:
  1. $(document);
    The first option will apply the jQuery library methods to a DOM object (in this case, the document object).
  2. $(‘#mydiv’)
    The second option will select every <div> that has the <id> attribute set to “mydiv”.
  3. $(‘p.first’)
    The third option will select all of the <p> tags with the class of “first”.
  4. $(‘p[title="Hello"]‘)
    This option will select from the page all <p> tags that have a title of “Hello”. Techniques like this enable the use of much more semantically correct (X)HTML markup, while still facilitating the DOM scripting required to create complex interactions.
  5. $(‘p[title^="H"]‘)
    This enables the selection of all of the <p> tags on the page that have a title that starts with the letter H.
These examples barely scratch the surface.

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

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:

CrossBad markup:
<script language="javascript">
alert('Hello World');
</script>
TickGood 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 cssRule9, which allows us to use Javascript to easily add CSS rules to the style sheet of the document. This means we can hide elements of the page using CSS—however the CSS is ONLY executed IF Javascript is running.

CrossBad markup:
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.

TickGood 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:

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

5. Further Reading

Further Reading: jQuery and JavaScript Practices

  1. jQuery Web Site: How jQuery Works10 and Tutorials11
    John Resig + Other Contributors
    One of jQuery’s true strengths is the documentation provided by John Resig and his team.
  2. 51 Best jQuery Tutorials and Examples12
  3. Easy As Pie: Unobtrusive JavaScript13
  4. Seven Rules of Unobtrusive JavaScript14
  5. Learning jQuery15
  6. Visual jQuery16
  7. jQuery Tutorials For Designers17
  8. jQuery For Designers18
    jQuery for Designers: learn how easy it is to apply web interaction using jQuery.
  9. 15 Days Of jQuery19
    jQuery tutorials and example code that takes you from zero to hero in no time flat.
  10. 15 Resources To Get You Started With jQuery From Scratch20
  11. The Seven Rules Of Pragmatic Progressive Enhancement21
  12. The Behaviour Layer Slides22
    Jeremy Keith
    Great slide notes giving a quick rundown on unobtrusive Javascripting.
  13. A List Apart: Behavioral Separation
    23Jeremy Keith
    A more in-depth explanation of the idea of separating Javascript into an unobtrusive “behavioural” layer.
  14. Unobtrusive JavaScript with jQuery24
    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

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

Footnotes

  1. 1 http://jquery.com/
  2. 2 http://jquery.com/
  3. 3 http://docs.jquery.com/Events/click
  4. 4 #Selectors
  5. 5 #Selectors
  6. 6 http://docs.jquery.com/Selectors
  7. 7 http://www.w3.org/TR/css3-selectors/
  8. 8 http://www.w3.org
  9. 9 http://plugins.jquery.com/project/jquerycssrule
  10. 10 http://docs.jquery.com/How_jQuery_Works
  11. 11 http://docs.jquery.com/Tutorials
  12. 12 http://www.noupe.com/tutorial/51-best-of-jquery-tutorials-and-examples.html
  13. 13 http://www.phazm.com/notes/javascript/easy-as-pie-unobtrusive-javascript/
  14. 14 http://icant.co.uk/articles/seven-rules-of-unobtrusive-javascript/
  15. 15 http://www.learningjquery.com/
  16. 16 http://www.visualjquery.com/
  17. 17 http://www.webdesignerwall.com/tutorials/jquery-tutorials-for-designers/
  18. 18 http://jqueryfordesigners.com/
  19. 19 http://15daysofjquery.com/
  20. 20 http://nettuts.com/javascript-ajax/15-resources-to-get-you-started-with-jquery-from-scratch/
  21. 21 http://ajaxian.com/archives/the-seven-rules-of-pragmatic-progressive-enhancement
  22. 22 http://adactio.com/atmedia2005/
  23. 23 http://www.alistapart.com/articles/behavioralseparation
  24. 24 http://simonwillison.net/static/2008/xtech/
  25. 25 http://en.wikipedia.org/wiki/Semantic
  26. 26 http://www.mezzoblue.com/archives/2005/05/30/who_cares_ab/
  27. 27 http://www.kottke.org/03/08/standards-semantically-correct
  28. 28 http://www.w3.org/TR/css3-selectors/

↑ Back to topShare on Twitter

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

Advertising
  1. 1

    Very informative article. Great examples, thorough and easy to read!

    p.s. Thanks for the plug!

    – Jon Hughes
    Notes from Phazm
    phazm.com/notes

    1
  2. 2

    Great Post as usual.

    1
  3. 3

    yesss I love jquery

    3
  4. 4

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

    5
  5. 5

    nice work!

    2
  6. 6

    Great review of why jQuery is worth using. :)

    0
  7. 7

    woow very nice article :) thank you

    0
  8. 8

    Whats the diference betwen using:

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

    instead of :

    $("p.hide-me-first").hide();

    1
  9. 9

    This post was incredibly well structured.

    Thanks for the informative article.

    -2
  10. 10

    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

    -4
  11. 11

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

    -2
  12. 12

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

    -1
  13. 13

    2expertsdesign.com

    September 16, 2008 1:14 pm

    great info

    -1
  14. 14

    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

    0
  15. 15

    jQuery!!!

    -2
  16. 16

    Great article!

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

    1
  17. 17

    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

    2
  18. 18

    quite a good article.

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

    -5
  19. 19

    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.

    1
  20. 20

    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

    0
  21. 21

    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.

    2
  22. 22

    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.

    4
  23. 23

    @Paul: http://www.dreamprojections.com/syntaxhighlighter/?ref=about

    Great article! I was waiting for this post ;-)

    0
  24. 24

    Thanks for the article, I’ll bookmark it for future use by jQuery newbies.

    @Paul
    I believe they’re using the SyntaxHighligher project.

    -1
  25. 25

    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

    -2
  26. 26

    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.

    -2
  27. 27

    very good article.
    Thank you.

    0
  28. 28

    @ 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

    -3
  29. 29

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

    0
  30. 30
  31. 31

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

    0
  32. 32

    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…

    0
  33. 33

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

    1
  34. 34

    Awesome post.. as usual

    2
  35. 35

    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

    0
  36. 36

    Super! Great article, keep it going!

    0
  37. 37

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

    -1
  38. 38

    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

    1
  39. 39

    On that last example.

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

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

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

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

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

    1
  40. 40

    jquery really rocks! Thanks guys for the tips :)

    1
  41. 41

    There is a cool comparison of the different js frameworks here:
    frameworks comparison

    0
  42. 42

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

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

    0
  43. 43

    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…

    0
  44. 44

    $(’#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

    1
  45. 45

    this is very very perfect!!

    0
  46. 46

    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!

    Adam McHugh – PHP Developer

    0
  47. 47

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

    0
  48. 48

    Awesome!

    How about Prototype, Mootools, Dojo, … ?

    0
  49. 49

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

    0
  50. 50

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

    1
  51. 51
  52. 52

    Smashing JQuery!

    0
  53. 53

    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?

    0
  54. 54

    Very useful, thanks! ^^

    0
  55. 55

    this is a really SM artical

    0
  56. 56

    Nice Articile , Thanks Lot

    0
  57. 57

    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.

    0
  58. 58

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

    0
  59. 59

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

    0
  60. 60

    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.

    0
  61. 61

    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.

    -1
  62. 62

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

    Stefan

    0
  63. 63

    Amazing!! will get started with JQuery today!!

    0
  64. 64

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

    0
  65. 65

    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.

    1
  66. 66

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

    1
  67. 67

    JQuery is yummy!

    0
  68. 68
  69. 69

    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.

    0
  70. 70

    Mootools. ;-)

    1
  71. 71

    i hate mootools

    Movie Octopus rules

    0
  72. 72

    Excellent….very helpfule for coming up developer……..

    gr8

    XHTML programmer

    0
  73. 73

    One typo…

    $(’p[title^=^"H"]‘)
    should be
    $(’p[title^="H"]‘)
    under Understanding Selectors: the Backbone of jQuery
    (not in the <code> block, but in the explanation)

    I love jQuery

    0
  74. 74

    @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/

    -1
  75. 75

    Great article!

    0
  76. 76

    “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″?

    0
  77. 77

    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

    0
  78. 78

    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!');

    0
  79. 79

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

    0
  80. 80
  81. 81

    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.

    0
  82. 82

    Moooooooooootools!!!

    -2
  83. 83

    Juan Pablo Barrientos Lagos

    September 17, 2008 7:53 am

    Rlly great article. Thx u.
    Regards!

    0
  84. 84

    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

    0
  85. 85

    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

    4
  86. 86

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

    0
  87. 87

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

    0
  88. 88

    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.

    0
  89. 89

    michaelaustinproductions.com

    September 17, 2008 11:01 am

    That is a great help. Thanks a lot. I love j query

    0
  90. 90

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

    0
  91. 91

    @ 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

    0
  92. 92

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

    1
  93. 93

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

    0
  94. 94

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

    0
  95. 95

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

    0
  96. 96

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

    0
  97. 97

    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.

    0
  98. 98

    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…

    -2
  99. 99

    this site has javascript errors… interesting.

    0
  100. 100

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

    0
  101. 101

    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!

    0
  102. 102

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

    0
  103. 103

    Great article! Very informative.

    0
  104. 104

    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.

    0
  105. 105

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

    0
  106. 106

    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!

    1
  107. 107

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

    1
  108. 108

    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.

    0
  109. 109

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

    0
  110. 110

    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

    0
  111. 111

    very informative, good job as usual!

    0
  112. 112

    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.

    1
  113. 113

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

    1
  114. 114

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

    1
  115. 115

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

    0
  116. 116

    @Roberto

    Check out the Live Query Plugin at Link

    Kevin Leary
    kevinleary.net

    2
  117. 117

    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.

    0
  118. 118

    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

    -1
  119. 119

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

    thanks to the author.

    0
  120. 120

    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.

    0
  121. 121

    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.

    0
  122. 122

    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.

    0
  123. 123

    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 !!!!

    0
  124. 124

    It’s really cool article for JQuery lovers.
    Thanks

    0
  125. 125

    please add me to the email list

    0
  126. 126

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

    0
  127. 127

    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

    1
  128. 128

    kereen

    0
  129. 129

    gr8 ,very easy to understand the basic of jquery

    0
  130. 130

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

    -1
  131. 131

    Nice and impressive article.
    thanks to the author.

    1
  132. 132

    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!!!

    0
  133. 133

    Nice article and easy to understand Jquery

    0
  134. 134

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

    1
  135. 135

    great post.

    0
  136. 136

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

    -1
  137. 137

    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.

    0
  138. 138

    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.

    1
  139. 139

    Totally agree with Mike (comment 137).

    0
  140. 140

    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.

    0
  141. 141
  142. 142

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

    1
  143. 143

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

    -2
  144. 144

    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…

    0
  145. 145
  146. 146

    Really awesome article man.. I Love JQuery….

    1
  147. 147

    oh God.
    I totally LOVE this article.

    1
  148. 148

    unique article

    0
  149. 149

    YESYES BEST

    0
  150. 150

    Phillip Matthew

    May 26, 2009 8:44 pm

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

    -1
  151. 151

    Phillip Matthew

    May 26, 2009 8:46 pm

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

    -1
  152. 152

    Amazing article, thanks!

    1
  153. 153

    fundamentalists...

    June 3, 2009 11:46 am

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

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

    0
  154. 154

    Can i use this article in my website?

    0
  155. 155

    good post. it really helps me :)

    1
  156. 156

    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.

    1
  157. 157

    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.

    0
  158. 158

    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.

    0
  159. 159

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

    -1
  160. 160

    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?

    0
  161. 161

    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.

    -1
  162. 162

    For using JQuery i suggest to try follow new free PHP IDE
    Codelobster PHP Edition with special JQuery plug-in.

    0
  163. 163

    It was a great Jquery help.
    It might useful to me.
    Thanks.
    __
    jquery help

    1
  164. 164

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

    1
  165. 165

    Very nice and useful tutorials to web designers,
    Thanks for posting.

    1
  166. 166

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

    0
  167. 167

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

    Thanks a lot.

    1
  168. 168

    Obviously, 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.

    -1
  169. 169

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

    0
  170. 170

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

    -2
  171. 171

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

    -1
  172. 172

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

    0
  173. 173

    php customization

    June 21, 2010 10:52 pm

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

    Thanks:-)

    0
  174. 174

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

    Thanks,
    Salsan Jose

    0
  175. 175

    Thanks 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

    -1
  176. 176

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

    -1
  177. 177

    @victor

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

    .cssRule adds a property to the whole class.

    -2
  178. 178

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

    What do you say?!

    -1
  179. 179

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

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

    Cheers!

    -2
  180. 180

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

    -3
  181. 181

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

    -3
  182. 182

    Hi priya you told is true

    -3
  183. 183

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

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

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

    0
  184. 184

    thanks it is great article …………

    2
  185. 185

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

    1
  186. 186

    Nice script…..

    0
  187. 187

    muhammad taahaa

    March 3, 2011 12:35 am

    very good work………..taahaa….

    -1
  188. 188

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

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

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

    0
  189. 189

    Very useful for the learners…

    0
  190. 190

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

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

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

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

    -1
  191. 191

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

    0
  192. 192

    great guide for a jQuery noob like myself.

    thanks!

    0
  193. 193

    Nice one..But how do you call an external js file that contains a jquery function from your html..I have a html form and an external jquery function that validates the 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

    -2
  194. 194

    Thanks for giving this data

    0
  195. 195

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

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

    -1
  196. 196

    Thanks 4 diz.

    -1
  197. 197

    This 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

    -1
  198. 198

    $(‘#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.

    2
  199. 199

    Very good article! Thank you!

    0
  200. 200

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

    3
  201. 201

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

    0
  202. 202

    Muhammad Hussain Wazir

    July 4, 2012 10:11 pm

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

    1
  203. 203

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

    0
  204. 204

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

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

    0
  205. 205

    Here are some points regarding jQuery best practice…. firstemission.blogspot.in/2013/01/best-practice-with-jquery.html

    0
  206. 206

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

    0
  207. 207

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

    -1
  208. 208

    simpal chaudhary

    March 25, 2013 11:23 pm

    Nice article…!!!

    0
  209. 209
  210. 210

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

    1
  211. 211

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

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

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

    0
  212. 212

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

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

    0
  213. 213

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

    0

↑ Back to top