Feed Sign in with OpenID OpenID

Simon Willison’s Weblog

jQuery for JavaScript programmers

When jQuery came out back in January 2006, my first impression was that it was a cute hack. Basing everything around CSS selectors was a neat idea (see getElementsBySelector) but the chaining stuff looked like a bit of a gimmick and the library as a whole didn’t look like it would cover all of the bases. I wrote jQuery off as a passing fad.

Over the past few months it’s become clear to me exactly how wrong I was. jQuery is an exceptionally clever piece of engineering. It neatly encapsulates an extraordinary range of common functionality, and provides a clever plugin API for any functionality not included by default. It takes a core abstraction—that of a selection of DOM elements—and extracts as much mileage out of it as possible. Most importantly, it does so in a way that obeys best practices and plays well with other JavaScript code.

Most introductions to jQuery focus on designers and inexperienced developers. I’m going to try to explain why jQuery should be of interest to experienced programmers as well.

Namespacing

The key to writing good, reusable JavaScript is to zealously manage your namespace. JavaScript provides a single global namespace (the window object), and many programmers (and some libraries) add symbols to this with abandon. Global variables are evil! Smart developers minimise their number of global objects, using techniques like the module pattern.

jQuery introduces just one symbol to the global namespace: the jQuery function/object. Everything else is either a directy property of jQuery or a method of the object returned by calls to the jQuery function.

What about language enhancements? Most libraries provide some variation of map, filter and strip, functions that are sadly missing from the JavaScript engines that ship with most browsers. Some libraries directly extend JavaScript’s built-in String and Array classes, but this can be a risky strategy. String.prototype and Array.prototype are themselves global namespaces, and adding properties to them brings the same risk of collisions as being careless with regular globals.

jQuery provides a number of language enhancement functions, but each one is made available as a property of the jQuery object: jQuery.each, jQuery.extend, jQuery.grep, jQuery.map, jQuery.merge and jQuery.trim. There’s no chance of these colliding with someone else’s code.

The infamous $ function

I wasn’t being entirely truthful when I said that jQuery was the only global symbol introduced: 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.

If you want the convenience of the $ function for jQuery without colliding with some other use of the global $ function, the jQuery documentation suggests the following idiom:
(function($) {
    // Within this block, $ is a reference to jQuery
    // Neat, huh?
})(jQuery);

Attaching everything to the $ symbol was one of the things that made me initially dismiss jQuery as a gimmick. For some reason thinking of it in terms of the jQuery symbol makes everything seem a lot more sensible, even though I’m happy to use the $ shortcut in my own code.

Selecting some elements

Every jQuery operation starts with selecting one or more nodes from the DOM. jQuery’s selection syntax (really a domain specific language) is an interesting hybrid of CSS 1, 2, bits of CSS 3, some XPath and a few custom extensions as well. I won’t describe it in detail here, but here are some useful examples:

jQuery('div.panel')
All divs with class=“panel”
jQuery('p#intro')
The paragraph with id=“intro”
jQuery('div#content a:visible')
All visible links inside the div with id=“content”
jQuery('input[@name=email]')
All input fields with name=“email”
jQuery('table.orders tr:odd')
“odd” numbered rows in a table with class “orders”
jQuery('a[@href^="http://"]')
All external links (links that start with http://)
jQuery('p[a]')
All paragraphs that contain one or more links

Of particular interest from the above are :visible and :odd, which are jQuery specific extensions. Also note that the attribute selectors use an @ sign, in common with XPath rather than CSS 2.

The selection language is extremely rich, and is similar to regular expressions in that time taken to learn it will pay off many times over.

Doing stuff with them

The object returned by a jQuery selector call is an interesting beast. It represents a collection of DOM elements, and behaves a bit like an array—it has a length property, items can be accessed by index and (most importantly) Firebug treats it as an array when displaying it in the interactive console. This is a clever illusion; the collection is actually a jQuery object, incorporating a large number of methods which can be used to query, modify and extend the collection of selected elements.

There are three principle categories of jQuery methods: those that manipulate all of the matched elements, those that return a value from the first matched object, and those that modify the selection itself.

I won’t list all of the methods (see visualjquery.com for that), but I’ll illustrate with some examples. If you have Firebug you can try these out interactively: use this Insert jQuery bookmarklet first to load the jQuery library in to any page, then paste the code examples in to the Firebug console.

jQuery('div#primary').width(300);
Set the width of div id=“primary” to 300 px.
jQuery('p').css('line-height', '1.8em');
Apply a line-height of 1.8em to all paragraphs.
jQuery('li:odd').css({color: 'white', backgroundColor: 'black'});
Apply two CSS rules to every other list item; note that the css() function can take an object instead of two strings.
jQuery('a[@href^="http://"]').addClass('external').attr('target', '_blank');
Add a class of “external” to all external links (those beginning with http://), then add target=“_blank” for good measure. This makes use of chaining, described below.
jQuery('blockquote').each(function(el) { alert(jQuery(this).text()) });
Iterate over every blockquote on the page, and alert its textual content (excluding HTML tags).
jQuery('a').html('Click here!');
Replace all link text on the page with the insidious “Click here!”.

Here are some examples of methods that read values from the first matched element:

var width = jQuery('div').width();
How wide is the first div on the page?
var src = jQuery('img').attr('src');
What’s the src attribute of the first image on the page?
var color = jQuery('h1').css('color');
What colour is the first h1?

There’s a pleasing symmetry at work here: the methods used to set attributes (when passed two arguments, or an object representing multiple settings) can instead be used to read values if called with only one argument. This symmetry is used throughout jQuery, making the API much easier to commit to memory.

Finally, there are methods that modify the set of selected elements itself. Many of these also provide simpler ways of traversing the DOM:

jQuery('div').not('[@id]')
Returns divs that do not have an id attribute.
jQuery('h2').parent()
Returns all elements that are direct parents of an h2.
jQuery('blockquote').children()
Returns all elements that are children of a blockquote.
jQuery('p').eq(4).next()
Find the fifth paragraph on the page, then find the next element (its direct sibling to the right).
jQuery('input:text:first').parents('form')
Find the form parent of the first input type=“text” field on the page. The optional argument to parents() is another selector.

Chaining

The jQuery team frequently boast about jQuery’s support of chaining, even to the point of declaring that “jQuery is designed to change the way that you write JavaScript” right on the front page. Personally I found this a big turn-off, so I’m happy to say that you can make good use of jQuery while avoiding lengthy chains of methods entirely.

That said, chaining can be used for some neat tricks. In addition to chaining a bunch of DOM manipulation methods together, you can use jQuery’s end() method to push and pop a stack of the selected element contexts. This is a little hard to explain; essentially, every time you use a method that changes the selected set of elements (such as children() or filter()) you can later use end() to revert back to the previous selection. Jesse Skinner gives a neat example of this in action in his tutorial Simplify Ajax development with jQuery:

$('form#login')
    // hide all the labels inside the form with the 'optional' class
    .find('label.optional').hide().end()
    // add a red border to any password fields in the form
    .find('input:password').css('border', '1px solid red').end()
    // add a submit handler to the form
    .submit(function(){
        return confirm('Are you sure you want to submit?');
    });

That whole thing is essentially a one-liner. It selects a form, finds some elements within that form, applies changes to them, reverts the selection back to the original form and assigns a submit() handler to it.

It’s a cute concept, but you don’t have to use it if you don’t want to. I’m quite happy splitting my code up with a few self-documenting variable names.

DOM manipulation

jQuery offers a few smart ways of making large scale manipulations to the DOM. The first is quite surprising: the jQuery function can take a snippet of HTML which it will turn in to a DOM element (it actually looks out for a string that starts with a less than sign):

var div = jQuery('<div>Some text</div>');

You can use chaining to add attributes to the div once it has been created:

var div = jQuery('<div>Some text</div>').addClass('inserted').attr('id', 'foo');

Now append it to the body tag:

div.appendTo(document.body)

Or prepend it to a known location using a selector:

div.prependTo('div#primary')

Handling events

All JavaScript libraries need an event handling utility and jQuery’s is no exception. As with attr() and css(), the event methods serve dual purpose: call them with a function to assign an event handler; call them without to simulate that event being triggered:

jQuery('p').click(function() { jQuery(this).css('background-color', 'red'); });
Set up paragraphs so that when you click them they turn red.
jQuery('p:first').click()
Send a fake “click” to the first paragraph on the page.

Similar functions exist for the other browser events—mouseover, keyup and so on. Note that within an event handler the ’this’ keyword is set to the element that triggered the event; using jQuery(this) is a common idiom to enable jQuery methods on that element.

A couple of event related functions deserve a special mention:

jQuery('a').hover(function() {
    jQuery(this).css('background-color', 'orange');
}, function() {
    jQuery(this).css('background-color', 'white');
});

hover() is a shortcut for setting up two functions that run onmouseover and onmouseout.

jQuery('p').one('click', function() { alert(jQuery(this).html()); });

one() sets up an event handler that will be removed after the first time it has been fired. The above example causes all paragraphs to alert their contents once the first time they are clicked.

jQuery also supports custom events, through the bind() and trigger() methods (for which click() and friends are just shortcuts). Custom events can take arguments, handled using an array passed to trigger():

jQuery(document).bind('stuffHappened', function(event, msg) {
    alert('stuff happened: ' + msg);
});
jQuery(document).trigger('stuffHappened', ['Hello!']);

Unobtrusive scripting

This is a topic that is very dear to me. I still believe that the best Web applications are the ones that are still usable with scripting turned off, and that the best way to achieve that is through unobtrusive scripting, with events being assigned to elements after the regular page has been loaded (see Unobtrusive Scripting and Hijax for more).

jQuery has excellent support for this. Firstly, the node selection metaphor is core to both jQuery and unobtrusive scripting as a whole. Secondly, jQuery ships with a solution to the window.onload problem based on Dean Edwards’ work getting a “DOM loaded” event to work cross-browser. You can set a function up to run when the DOM is ready for it like so:

jQuery(document).ready(function() {
    alert('The DOM is ready!');
});

Even better, you can shortcut the above by passing your function directly to jQuery():

jQuery(function() {
    alert('The DOM is ready!');
});

jQuery and Ajax

jQuery has the best API for Ajax I’ve seen in any of the major libraries. The most simple form of an Ajax call looks like this:

jQuery('div#intro').load('/some/fragment.html');

This performs a GET request against /some/fragment.html and populates div#intro with the returned HTML fragment.

The first time I saw this, I was unimpressed. It’s a neat shortcut, but what if you want to do something more advanced like display an Ajax loading indicator? jQuery exposes custom events (ajaxStart, ajaxComplete, ajaxError and more) for you to hook in this kind of code. It also offers a comprehensive low-level API for more complex Ajax interactions:

jQuery.get('/some/script.php', {'name': 'Simon'}, function(data) {
    alert('The server said: ' + data);
}); // GET against /some/script.php?name=Simon

jQuery.post('/some/script.php', {'name': 'Simon'}, function(data) {
    alert('The server said: ' + data);
}); // POST to /some/script.php

jQuery.getJSON('/some.json', function(json) {
    alert('JSON rocks: ' + json.foo + ' ' + json.bar);
}); // Retrieves and parses /some.json as JSON

jQuery.getScript('/script.js'); // GET and eval() /script.js

Plugins

Considering the amount of functionality you get out of the box, jQuery is actually pretty small—it comes in at 20KB when minified, even smaller when gzipped. Additional functionality outside the framework is handled using plugins, which can (and do) add brand new methods to the existing jQuery instance object. If you want to be able to run:

jQuery('p').bounceAroundTheScreenAndTurnGreen();

jQuery’s plugin mechanism provides documented hooks for adding that method to the jQuery system. The ease with which these can be created has attracted an impressive community of plugin authors; the Plugin directory lists well over 100.

One really nice touch is that you can add custom selectors in a similar way to custom methods. The moreSelectors plugin adds things like “div:color(red)” to match divs with red text, for example.

Leaky abstractions

In my new-found respect for jQuery, I’ve been struggling with one philosophical blocker. For the past few years, I’ve been advising people to only pick a JavaScript library if they were willing to read the source code and figure out exactly how it works. My reasoning was based on Joel Spolsky’s classic essay The Law of Leaky Abstractions, which points out that the more complexity your APIs are hiding, the more trouble you’ll be in when some of that complexity leaks through. Browsers are the leakiest abstraction of them all, so being able to dig yourself out of a hole when the library fails to cover for you is of paramount importance.

jQuery uses some really arcane tricks to achieve its functionality—parts of it (like the selector code) are positively terrifying. If understanding exactly how the library works is necessary, jQuery must be a poor choice for the majority of developers. However, the enormous popularity of jQuery combined with a distinct lack of horror stories demonstrates that this is not the case.

I think I’m going to have to reconsider my advice. The way the library works isn’t the issue: it’s understanding the underlying issues, and knowing what kind of browser differences there are and what kind of techniques your library is using to fix them. No library can protect you 100% against weird browser behaviour, but as long as you have a grounding in the underlying theory you should be able to figure out if a problem stems from your own code, your library or the underlying implementation.

To conclude

I hope I’ve made the case that jQuery isn’t just another library—there are enough interesting ideas in there to teach even the most hardened of JavaScript programmers some new tricks. Even if you don’t intend on using it, it’s still worth spending some time exploring the jQuery ecosystem.

This is jQuery for JavaScript programmers by Simon Willison, posted on 15th August 2007.

Tagged , ,

View blog reactions

Next: Designing for a security breach

Previous: A note about simple registration

76 comments

  1. Threw this into #jquery on FreeNode. Feel free to hang out there ;)

    Nick Q - 15th August 2007 03:12 - #

  2. This should be required reading for anyone starting out with jQuery.

    Brandon Aaron - 15th August 2007 04:17 - #

  3. the key to jquery's success i think is the selector. a good selector, addEventListener normalizer and at a lower priority, a style normalizer does the trick well.

    jquery's brevity was my initial appreciation for it - but its selector was what i was really after.

    daaku - 15th August 2007 04:24 - #

  4. Good stuff, it would be nice if there was a printer friendly page...

    Fred - 15th August 2007 05:13 - #

  5. @fred:

    well just use jQuery to make it printer frindly:

    javascript:var%20s=document.createElement('script' );s.setAttribute('src',%20'http://code.jquery.com/ jquery-latest.js');document.body.appendChild(s);s. onload=function(){var content=$( '.entryPage' );$( 'body' ).remove( );$( 'html' ).append(content);};void(s);

    sifu - 15th August 2007 08:52 - #

  6. jQuery is definitely a popular utility function library, but the sheer amount of dual/triple/quadruple special-case uses for both function calls and method names is an instant turnoff for me.

    The jQuery object itself can perform a selector query, embed a DOM element, create a DOM element from HTML and assign a DOMContentReady event handler - and probably more. Event handling is separated into separate methods for each event type. Some method names make no immediate sense, like .one or .eq, and you can't immediately tell if a method acts on the first element in the collection or all of them.

    I can't recommend jQuery to the developers I am mentoring because it is in itself a completely separate abstraction, and a muddy one at that. They will end up having to learn jQuery instead of having to learn DOM, CSS and JS, and when being considered as a direct replacement for those it fails both due to complexity and inconsistency.

    Thor Larholm - 15th August 2007 09:07 - #

  7. Thanks for a great behind-the-scenes walkthrough. The end() method was a new discovery to me...

    Björn Rixman - 15th August 2007 09:19 - #

  8. Very nice article - I've added it to the official tutorial list on the jQuery page.

    digitalspaghetti - 15th August 2007 10:54 - #

  9. Thor: I thought the overloading of the jQuery function and associated methods was dumb too - but I've actually found that it made it much easier to learn the library. jQuery has its own internal consistency - once you learn the basic principles (which I've tried to outline in this article, since I haven't found them in one place before) educated guesses about what something does tend to work out. And like Python, if I'm unsure of anything I just fire up the Firebug console and test it interactively.

    You're absolutely right that jQuery is the wrong way to go if you are just starting out with CSS and the DOM; I tried to address that in that last bit on leaky abstractions. Unfortunately, as with any powerful tools (think IDEs) you will get inexperienced developers using them in place of learning how stuff actually works (see Rails), but that's certainly not a reason for experienced developers to avoid them.

    Simon Willison - 15th August 2007 11:09 - #

  10. I've been quite happy with jQuery, it's great for people used to CSS & the DOM. Hoever, I have had one issue with using it for AJAX with Safari (crashing).
    http://groups.google.com/group/jquery-en/browse_th read/thread/e01c36f766f86faa/f064b0568e562f9e?lnk= gst&rnum=1#f064b0568e562f9e

    AlastairC - 15th August 2007 13:00 - #

  11. Excellent! I have never used jQuery before and this was an superb introduction. Thank you.

    Tony Pitale - 15th August 2007 13:36 - #

  12. Thanks for this article. I've seen people raving on about jQuery before but the emphasis was always on that crazy chaining (which I'll end up doing initially but as soon as anything unexpected happens you need to split things into intermediate variables anyway). The amount of overloading *is* disgusting but as you say, it's consistent so it's not so bad. As it stands I'll probably use jQuery for my next project. The plugins were the thing that finally won me over. That being a nice alternative to going to big, bloated heavyweight libraries like dojo for lots of functionality.

    Frankie Robertson - 15th August 2007 13:53 - #

  13. Nice article, I've always been a fan of coding raw JavaScript but I think I'll have to give jQuery a shot. I've bookmarked this page for future reference.

    Jon Lee - 15th August 2007 15:33 - #

  14. With docs.jquery.org being down a lot lately, this makes an excellent reference. Thanks for taking the time to put this together.

    Scott Johnson - 15th August 2007 16:49 - #

  15. Er, that's docs.jquery.com.

    Scott Johnson - 15th August 2007 16:50 - #

  16. Should probably use the packed version of the library in the Insert jQuery bookmarklet. No sense creating extra traffic for jquery.com if you're not looking at the library...

    javascript:void(function(){var s=document.createElement('script');s.src='http://j queryjs.googlecode.com/files/jquery-1.1.3.1.pack.j s';document.getElementsByTagName('head')[0].append Child(s);}())

    Happy Steve - 15th August 2007 17:48 - #

  17. Are there not some performance implications though when using the CSS selector syntax?

    For example, $('#myid') must be significantly slower to return than the DOMs getElementById.

    Perhaps not worth worrying about on a one off, but in a very heavy application where performance is of critical concern, do you still think it is viable?

    Andy Hume - 15th August 2007 19:04 - #

  18. Andy: selector performance is actually pretty good - it's well optimised (there's actually a special case to shortcut getElementById) but it still won't be as fast as document.getElementById. That said, it all depends on what your application is doing. I'd be cautious about using jQuery selectors inside an ondrag event that fires many times, but for most other events the overhead isn't likely to be noticable.

    Simon Willison - 15th August 2007 19:13 - #

  19. Nice write up Simon, I've been using jQuery for behavior in our CMS, having dropped prototype for the simple reason that jQuery sells itself with: Write less. Do more.. I've learned a few new tricks from this post :-)

    Mike Papageorge - 15th August 2007 19:52 - #

  20. jQuery is my framework because I believe its heart and focus are in the right place: _functionality_. It is one of the first frameworks to specifically address simplicity and speed, solving cross-browser issues and JScript shortcomings in the most popular areas. It is cool by form & function, rather than by purpose - Prototype and Mootools, etc., may look slick but have a huge overhead, and are not nearly as well documented. jQuery saves time for all of us, as well as teaching us important lessons - my CSS and JS code has improved in practices and readability thanks to the proper influences from the jQuery community - and in the end, the saved time means more sanity, and often, more money. Hopefully, the practices in jQuery will one day find themselves in an ECMAscript spec.
    Until then, it is this community support which will help awaken the less-fortunate who don't yet know the power of jQuery. Many thanks, Simon.

    Charles Phillips - 16th August 2007 00:04 - #

  21. This is a huge reason I created DED|Chain for YUI. I loved the jQuery syntax so I figured YUI needed an appropriate facade to sit on top of it all.
    see: http://dedchain.dustindiaz.com

    Dustin Diaz - 16th August 2007 06:38 - #

  22. I think I came at jQuery from the opposite end. Initially I really liked the compactness it brought to code and was always a big fan of really consise JavaScript but recently I've been called in to work with other peoples jQuery apps and found it to be ludicrously idiomatic to the point of extreme annoyance. The extra level of abstraction, as an experienced JS coder, is just another mental leap I'd rather not make. I'm sure a good code would write beautiful code with jQuery but I think it actually encourages an unreadable style slighty.

    For a start, it's promoted that huge amount of chaining and subsequent idiom of laying out one huge statement over many lines which is, in my opinion, pretty horrible to look at.

    I agree with Thor as well, the general all-purposeness of the jQuery/$ function is a headache in understanding other peoples code as are some of the difficult function names.

    The other thing that I found when using jQuery was that because it's so centered around elements as soon as you step away from that arena you are in the dark. I like all the additions to String, Function and Array that Prototype gives me (I'm not sure adding to their prototypes is as much of a problem as you make out) and use them heavily. When I use jQuery I end up writing them anyway.

    That being said though, I do really like its convenience for light scripting and the ideas and engineering are excellent.

    I love that namespace idiom thing as well. Something that could make YUI a bit more manageable no doubt.

    Dan Webb - 16th August 2007 12:36 - #

  23. And if you like Ruby, _why's Hpricot, a "fast and delightful HTML parser", began its life as a recombinant clone of jQuery genes! ~L

    L - 16th August 2007 17:45 - #

  24. Nice overview, Simon. I've ignored jQuery up until now, but thanks to your writeup, I think I'll be checking it out soon.

    Martin Kenny - 17th August 2007 13:43 - #

  25. Footnote: the script link on the getElementsBySelector page you link to is broken; it points to

    http://simonwillison.net/js/getElementsBySelector. js

    which gives me a 404. The demo on the same page fetches the file from:

    http://simon.incutio.com/js/getElementsBySelector. js

    Fredrik - 17th August 2007 15:51 - #

  26. Thank Fredrik; I've fixed those links now.

    Simon Willison - 19th August 2007 21:00 - #

  27. I've been using JQuery a lot, initially attracted by the documentation and now by the neat model.

    Regarding leaky abstractions, one trick I sometimes use as a last resort is the get() method, which lets you say goodbye to jQuery world and work with raw DOM elements. e.g. $("img").get() gives you all img DOM objects.

    Michael Mahemoff - 20th August 2007 02:20 - #

  28. There has been some discussion about this post over at Nabble.com

    Thor Larholm - 20th August 2007 19:43 - #

  29. Hi Simon,

    I like the honesty throughout your entire blog and your "sharing" nature with the knowledge you have / have learnt is a big plus for the whole online community. Please, keep up the good work.

    Gavin Baumanis - 25th August 2007 12:13 - #

  30. really, really... jQuery is good stuff to javascript programming, is there anybody out there that not loves the $ shooort-cut too...?

    pateketrueke@gmail.com - 27th August 2007 11:56 - #

  31. I thought I knew jQuery well, considering I've been using it for quite a while... but then I read this and found things I didn't even realize!

    Montoya - 30th August 2007 14:50 - #

  32. Yes jQuery is COOL!

    My Learning and Test:
    http://geelake.com/usCalendar/

    uscal - 4th September 2007 03:19 - #

  33. Thanks for a nice article!

    George - 12th September 2007 18:29 - #

  34. Excellent! I have never used jQuery before and this was an superb introduction. Thank you.

    riper - 27th September 2007 16:13 - #

  35. I'm just wondering if (and how) jQuery could feed the event handler function a scope (like the bind() method in Prototype).

    Is it possible? (wrong place to ask, perhaps, but being a "jQuery is this and not that" discussion...)

    Claudio Cicali - 7th October 2007 14:51 - #

  36. Thanks for this very useful piece. For anyone starting to do code walk-throughs of jQuery, first make sure you are clear on the optimal use of of prototypes. Douglas Crockford's site is a great resource in this regard: http://javascript.crockford.com/prototypal.html. Also note that the jQuery object declaration uses the object literal syntax. The following two links are worth a look in that regard.
    http://www.digital-web.com/articles/objectifying_j avascript/
    http://dean.edwards.name/weblog/2006/03/base/
    Brush up on regex statements if need be, and after that it is divide and conquer.

    The great thing is I can use jQuery immediately, and concurrently, progressively develop a high- and low-level understanding of the code to the extent necessary or desired.

    Thanks Simon, and thanks to John Resig and jQuery contributors.

    kcease - 7th October 2007 17:17 - #

  37. dude.. nice tutorials, thanks in advance!!!

    fling - 28th November 2007 07:54 - #

  38. I "discovered" jQuery yesterday.
    It is the first Javascript API I decided to learn and use, after researching for a while.
    I am really impressed, excited, amazed about jQuery.
    Thank you very much!

    I don't have time to learn the other libraries. The "jQuery minute" is worthwile. Congratulations!

    J Bruni - 20th December 2007 03:57 - #

  39. Hi Simon,

    How long (Hours) it will take to learn jQuery for prof. programmer?

    Expert - 20th December 2007 20:23 - #

  40. cooool!

    jackzheng - 29th December 2007 05:39 - #

  41. Hi Sam, Thanks for this write down on JQuery. Pity I have to come on board after a whole year. Never the less am glad I did. Jquery is superb, no doubt about that. My major concern is that it shouldn't be for beginners. Back in my school days, in the Art class, I always dwelled on drawing abstract stuff. My classmates we always impressed, but still I got low marks. My teacher insisted I should first master the basics. Now I understand why. To a beginner, jquery will be a whole new language. Even designer interested should first have the basics in JS, CSS, DOM and HTML for that matter. Otherwise jquery is brilliant for javascript programmers because it speeds up coding. Personnally I pretend the library is compiled, like C and try not to break it apart or modify it.

    Alfred Okedi - 21st January 2008 17:53 - #

  42. jquery - J think is a popular utility function library in Poland. I use tihis library and my friends too. Thanks for good stuff.

    Jarek - 28th February 2008 08:59 - #

  43. Really nice introduction to jQuery. Thanks.

    Jonah Dahlquist - 29th February 2008 16:18 - #

  44. Hi Simon,

    Thanks for taking the time to post this entry. I'm a consultant recently assigned to a company that uses jQuery, and this article really helped me get up to speed on the basics. :)

    Take care and thanks again,
    Jen M.

    Jen - 10th March 2008 13:29 - #

  45. I am trying to add(prepend) rows into a table but I want them,as they are added, to be after the HEADER row. Any Ideas?

    KG - 17th March 2008 22:18 - #

  46. Thank you for this great article! I am just starting out learning jQuery after having dived deep into YUI. It's great to read the highlights and know better about how to approach this library.

    Andrew Wooldridge - 25th March 2008 17:11 - #

  47. Excellent overview of JQuery. I have added this article as must-to-read on JQuery for the developers of my company.

    HT - 15th April 2008 00:48 - #

  48. Is there any function in jquery that we can call after any oblect loads ? eg. "afterload" ?

    Dhaval Patel - 6th May 2008 08:30 - #

  49. Why are there spaces after the : in your CSS? Have you learned nothing from jQuery minimizing their code for you? In client-side script, whitespace==bloat! (Also, named colors are for babies.)

    Blah:
    .css{color: white; background-color: black;}
    .css({color: 'white', backgroundColor: 'black'})

    Yay:
    .css{color:#FFF;background-color:#000;}
    .css({color:'#FFF',backgroundColor:'#000'})

    Matt - 15th May 2008 20:06 - #

  50. In response to Matt, that whitespace = bloat in client code, that's true. However, if your browser accepts HTTP compression (all do) and your server will serve with HTTP compression (there's almost always a way), these are non-issues. If you must write in an interpreted language like JavaScript/HTML, find a way to make your code readable and have the technology handle the compression.

    Daniel Rosenstark - 28th June 2008 04:36 - #

  51. Thank you - just beginning to get my head round this one!

    Fred Campbell - 18th July 2008 10:44 - #

  52. If adding to globals is bad, wouldn't augmenting jQuery with your own functions be just as bad?

    Riomoto - 5th August 2008 06:00 - #

  53. Lets says if i open a browser window using File -> New -> Window.
    I am wondering if Jquery creates a handle or reference to the browser
    window and stores it in Jquery Object.
    This kind of information will be very helpful to detect if browser has
    multiple windows opened.
    Please let me know if its possible to do with Jquery

    bansi - 28th August 2008 17:11 - #

  54. Great Article. I'm an old school JS programmer from when AJAX was still called DHTML and I've been avoiding frameworks like a plague. With the "Ajax Experience" conference in Boston coming up and 3 classes based entirely on a single framework I've been doing my research on which one I should go with.

    Your write up here not only made it clear that jQuery was the one for me... but also actually turned me on to the idea of giving it a real shot in a production environment.

    Great read, awesome examples... keep it up.

    chadillac - 19th September 2008 01:44 - #

  55. @bansi

    I don't know if jQuery or any framework is capable of that functionality. I've written some apps that have to use window tracking and cross window communication (e.g. web based instant messaging using pop ups).

    A window can only track another window if that is indeed the parent window that spawned it... this is mostly due to sandbox security (which thank god exists or all our bank accounts would probably be hijacked).

    My way around this was basically cross window communication.

    [[ parent window ]]
    var myPopUps = array();
    ===================

    [[ child window ]]
    var locBuffer = parent.location;
    function checkParent()
    {
    if (parent.location != locBuffer)
    {
    reportIn();
    locBuffer = parent.location;
    }
    }

    function reportIn() { parent.window.myPopUps.push(this);
    }

    window.setTimeout('checkParent',1000);
    ========================

    I know it's not the cleanest method, but it's worked for me. Also note that code isn't tested was just trying to show the idea. (e.g. passing 'this' to the parent window may not correctly pass the window object/reference)

    chadillac - 19th September 2008 01:54 - #

  56. Deja vu. I went through the same awakening with JQuery and that was after trying at least 5 or 6 alternatives (including building my own). JQuery is a work of art, and after 40 years of programming, has helped rekindle my enthusiasm for coding.

    Eddie - 19th September 2008 10:38 - #

  57. need to sound with oop

    rocon - 22nd October 2008 06:01 - #

  58. Here is a great article on howto write your own custom functions in jQuery.

    Great article Simon

    Learning jQuery - 5th January 2009 13:37 - #

  59. Hey - I just found this jQuery Cheat Sheet for the iPhone on iTunes. Sweet!

    http://itunes.apple.com/WebObjects/MZStore.woa/wa/ viewSoftware?id=302090867&mt=8

    Frank - 16th January 2009 19:52 - #

  60. Well written and informative article.

    Malcolm Swaine - 13th March 2009 21:15 - #

  61. i want to learn jquery from beginning

    ajay - 11th April 2009 11:43 - #

  62. Simon, great article you got there. I was also skeptical about jQuery when I first saw it, and was trying to understand why is everyone using it and hyping over it all the time these days. Made a blog post inspired by and linked to yours.

    Alex - 25th April 2009 22:43 - #

  63. Be enjoy to take a look the jQuery beatiful sample

    http://railsgeek.com/my_jquery_samples.html

    I really like the semantics of jQuery, is fairly short and predictable.
    Look at the code, it is not overloaded with ambiguous and unclear structures.
    Like Ruby, the methods often returns a jQuery object, so you can create a chain of methods. I want to share the code that I wrote last night. If you are not familiar jQuery, so look over the code.

    mikhailov - 22nd May 2009 12:24 - #

  64. I was studying with jQuery from 2008 and and after reading this tutorial I made myself retouched on some jQuery samples, thanks for sharing this post :)

    Shahriat Hossain - 31st May 2009 10:19 - #

  65. Damn.. I'm still not convinced. May be I'm just a control freak but I don't like not knowing what's going on under the hood. I'd prefer to start with something like DOMAssistant but I hate the $() function. I do *love* Flow.js (Flowjs.com) but it seems to be dead.

    abc - 4th June 2009 20:02 - #

  66. jQuery is great! Actually its the logical successor of the failed/failing CSS/HTML specification in many ways.

    Lets face it, CSS is already here since 1996 and it didn't came very far since then. Better yet, it got inconsistent right away with pseudo-classes like :hover which is of course a behavior and not a style! Not to mention the schizophrenic ideas about what the width of a component is. Yes, CSS seems like enough at first, but knowing XPath... CSS is a poor way of selecting components in a document to style them. jQuery's selection mechanism however, is where CSS should have been 10 years ago!

    Then some say chaining is a bad/ugly way of programming. I can not agree with that statement. Chaining immediately shows you the context of the object(s) you work on. Ok, maybe some people make a mess of it, but I read many different source code projects (and that's certainly not only JavaScript) and I tell you; chaining or no chaining, its always possible to make a mess out of it! Actually its for compilers a lot easier to optimize chains then it is to optimize single method commands per line with their value stored in variables, and use them in many places (its so easy to make a mess of that as well)! Besides, chains work on the Stack, and variables on the Heap.

    Some people find that the method names make no immediate sense... Well, ever worked with libc? It comes down to this, if you want to work with a library, then you have to start somewhere. If you started and keep on working with it, you'll see that you will remember it better. And if your using it really a lot, its actually immediately clear what .one and .eq mean and it saves you a hell of a lot of typing if your using it a lot. Also you will see that shortcuts like .click and .hover ARE handy, but if you like you can use .bind for all that of course.

    Although I understand Joel Spolsky’s ideas; in the real non Javascript world, a lot of people do not read the Java rt class library either. If a bug pops up (and Java is incredibly buggy as well!) can you blame the programmer of the application for not understanding what is happening inside the Java rt class library and therefor drop the platform.... well, I'm sure some people would say yes! Javascript is fun and a great language in theory but even worse then Java... The language it self contains bugs!

    And then to conclude, I DO recommend jQuery. If you are a teacher, explaining how webpages work, its probably wise to skip the whole Javascript part in the first place. Believe me, CSS will be a mind boggling thing to crasp for newbies in the first place, especially when you want to have cross-browser compatibility. If you want to introduce them to the Javascript part... just talk about the basic idea of the DOM (which you already do in order to use CSS) and go as fast as you can to the jQuery library! If you are a web developer... I mean for work, don't wait but download it!

    johan - 10th June 2009 11:39 - #

  67. Being a beginning web developer I'm not experienced in serious JavaScript coding. Just the basics for what I need so far. I decided a few weeks ago to get (much) more into JS, mainly for normal web site- and CMS behaviour I came across jQuery. I couldn't decide to focus on jQuery or plain JavaScript, but this article and the good comment of Johan convinced me. I mainly agree with the JS pro's that you need to understand first all that's going on under the hood. But tell me: what if you have serious knowledge of HTML/CSS and partly the DOM (like me), and you had to start digging into JS today? To me jQuery looks the way JS should be written. I love the simplicity and if there is no heavy application building involved I don't see a reason not to love it. As I use it more and more I will get more experienced in jQuery and plain JS. It reminds me my teacher 3 years ago explaining us the importance of framesets (duh?)...things evolve, I guess. Thanks for the great, great article!

    NicoF - 15th June 2009 00:01 - #

  68. I would like to update div content displayed in the following form :

    <div id="tv">
    <div id="player">
    </div>
    </div>

    $("#player").html(...funtion to update...

    It doesn't work :(

    How can we call $("#tv").$("#player")... ???

    Thank you

    Djerba - 4th July 2009 15:35 - #

  69. Try
    $("#tv, #player")....

    NicoF - 9th July 2009 22:38 - #

  70. it is very useful for first time JQuery learner

    rik - 20th July 2009 07:46 - #

  71. Iam a beginner of JQuery. I never expected the things that can be achiveable with Jquery. We can reduced lots of client side scripting with Jquery. Tons of thanks
    Prawin

    prawin - 26th August 2009 12:51 - #

  72. gegg

    gf - 10th September 2009 10:44 - #

  73. For anyone who's interested I've published V2 of my jQuery reference from one of the articles featured on here. I don't work there any more so it's not maintained. If you want to have a look at that it's here: http://www.skidoosh.co.uk/jquery/jquery-selectors- and-attribute-selectors-reference-and-examples-v2/ I'll be updating it for 1.3 in a few days.

    Skidoosh - 19th November 2009 23:52 - #

  74. This is by far the best writeup of jQuery I've read and there's a _lot_ of stuff out there on internet.

    I'm extremely thankful for the spark of idea of jQuery objects. Those things have always confused me when I try out stuff with firebug.

    Jeffrey Jose - 12th December 2009 13:05 - #

  75. Note: In jQuery 1.3 [@attr] style selectors were removed (they were previously deprecated in jQuery 1.2). Simply remove the '@' symbol from your selectors in order to make them work again.

    See http://docs.jquery.com/Selectors

    Gringo - 7th January 2010 23:28 - #

  76. jQuery rocks!

    Nice article! One more bookmark to my jQuery bookmark folder!

    sandesh magdum - 15th January 2010 09:51 - #

Comments are closed.
A django site