Hacker News new | past | comments | ask | show | jobs | submit login
Things You Might Not Know about jQuery (oreilly.com)
118 points by fogus on Jan 6, 2011 | hide | past | favorite | 26 comments



The first example for the 2nd point is wrong:

   The following two lines have the same effect, for example:

   $('pre').attr("css", {backgroundColor:"gray"})
   $('pre').css({backgroundColor:"gray"})
Not correct. The first line will create an attribute called 'css' while the second line will change the 'style' attribute. The author probably meant something like:

   $('pre').attr("style", {backgroundColor:"gray"})
   $('pre').css({backgroundColor:"gray"})
...but even these two lines are not exactly the same. The first one will reset the style attribute to the given value while the second line will just change the backgroundColor value in the style attribute.


He is claiming that the value "css" is special, along with a few others, in that when you call attr with it jQuery actually dispatches to the css method passing the second argument as the value. He claims in the comments that this works with 1.4 (http://answers.oreilly.com/topic/2353-5-things-you-might-not...), but I can't find it documented anywhere in jQuery's docs, nor can I make it work with the version of jQuery served on the jQuery docs site itself.


IIRC from the last time I browsed through jQuery source, attr('css', ...) is used internally but didn't look like it was meant to be exposed as a public method. And I never remember seeing this sort of special case in the docs. So, I wouldn't recommend using it in kosher jQuery code. A lot of things in this article seem a little dated; almost every tutorial now covers the $(function() {}) shortcut, and event binding is something I wouldn't know about jQuery? Really.

Note to jeresig: this article illustrates a beef I remember passing on when the jQuery docs reorganized; it works well as API reference now, but before, introductory text for each section of the docs describing things like event namespacing made for a nicer introduction to beginners like me, as well as the structured sub-organization of methods within each section. Now, it's more of an alphabetical method soup, so a lot of beginners probably never bother to learn that event namespaces exist, or what the jQuery event object does. For example, you can only get to the documentation on the event object from within the documentation for methods like .bind(), which I find odd. (How would a beginner know that it even existed unless they went specifically to the .bind() docs in an alphabetical list of other cooler sounding methods?)


The second example doesn't work for me.

var image = $("").appendTo("body"); //Nothing appended to body.

I think it should be:

var image = $("<img>").appendTo("body"); //img node appended to body.


It looks like the `<img/>` in between the quotes was not escaped; it's in the source.


The first sentence really stops me from reading it

jQuery is a very powerful library, but some of its powerful features are obscure, and unless you've ready the jQuery source code, or my new book jQuery Pocket Reference, you may not know about them.

Why don't you give me the article first, let me read it, get amazed by the techniques and then find out about you and your book and feel like I need to read another book.

This way I feel like you are trying to sell me your stuff.


Perhaps because you are reading an article in O'Reilly's website, whom sells David Flanagan. That out of the way, I thinkn he's entitled to a little self promotion at any point in the article since this is the man behind such gems as JavaScript: The Definitive Guide, and The Ruby Programing Language.

He is trying to sell you stuff, but honestly you should go right ahead and buy what he's advertising because his books are really that good.


Seconded. Advertising for outstandingly good products is not a bad thing.


[deleted]


Yeah I noticed it too late to edit the post. I'm on the 30th hour of a coding marathon and I'm starting to feel my neurons burning up and leaving me numb as hell. You can easily spot places where my train of thought kind of crashed into a wall. Oh well, c'est la vie.


What's wrong with him trying to sell his stuff to you? It's not obtrusive, the content is valuable. Heck, he's not even selling you, via adverts.

Are you under some illusion that sites run by for-profit companies have a primary purpose other than to sell you their stuff?

Maybe it's a little offputting. But I'd put dollars-to-donuts that if it was A/B tested, they would generate a lot more revenue with the notice at the top. (Edit - just noticed there was no purchase link, so it would need to be changed to easily A/B test...)


Except that there's no link to the book which I suppose one could consider more or less intrusive.


Especially considering these are almost all jQuery 101 tips, e.g. things people learn within the first month of using jQuery. It's not like these are crazy secrets. I was also quite put off by the "check out my book" reference in the very first sentence.


You don't have to use $(document).ready() anymore

As far as I know, this was always the case. The reason people use $(document).ready() is that it feels more correct, is more consistent. jQuery() supports three distinct behaviors:

    $(function)   => jQuery(document).ready(function)
    $(objects)    => Wrap objects with jQuery functionality
    $("selector") => Find objects, and wrap them with jQuery functionality

One of these is not like the others.


Actually, there are four!

    $("<tag>") => Make a DOM element and wrap it
This wild overloading of $ is one of the things I find hard to deal with in jQuery.


Doh, that's right, and it is one of the coolest and most fun to abuse features of jQuery.


The only thing on this list that I didn't already know was that you could bind "ajaxStart" and "ajaxStop". This will prove very useful in the future.



could somebody please post an example to point #1?


Instead of:

    $(document).ready(handler);
you can write:

    $(handler);


commonly used like this:

    $(function() {
      // write the stuff you normally put in $(document).ready( ... );
    });


Just in case anyone finds it useful, use this when you have to mix jQuery with other JavaScript libraries like prototype:

    jQuery(function($) {
      // your code using $
    }(jQuery));
This way you can use $ to reference jQuery in your code even if the other library took control of $ in the global scope.


You don’t need that jQuery parameter (in fact, I think that makes it invalid JavaScript). ie.

  jQuery(function($) {
    // your code using $
  });
You might be thinking of the recommended method of creating a closure, in which the code is executed immediately rather than upon page load:

  (function($) {
    // your code using $
  })(jQuery);


It's not invalid JavaScript, and it does work, but it isn't doing exactly what he thinks it's doing.

You need the jQuery parameter to make sure the $ in your code refers to the jQuery object and not something else. Without it your code is just referencing the global $ object which some other framework could have poached for itself.

But I suspect you already know all that. What his code is actually doing is creating an anonymous function intended to provide a safe place for $-based code, evaluating it immediately, and then passing the return value to the jQuery function. Depending on the return value this may be useful or not, but I'm pretty sure it's not what he intended. His function is evaluated immediately rather than when the DOM is ready.

What you want to do is combine the second part of your example with your already-written code:

    (function($) {
      $(function () {
        // your code to fire when the DOM is ready
      });
    })(jQuery);


You are correct. That was a mistake from my part.


We went with jQuery in no conflict mode when we needed to mix jquery and the prototype lib for ads.

from the docs:

  var j = jQuery.noConflict();
  // Do something with jQuery
  j("div p").hide();
  // Do something with another library's $()
  $("content").style.display = 'none';


The article should really note that the latter is just an alias for the former.

It reads as if the author is trying to say that the reason for using $(document).ready(handler) - to wait to run certain functions until the entire DOM has loaded - is no longer necessary.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: