Gmail Calendar Documents Reader Web more »
Recently Visited Groups | Help | Sign in
Google Groups Home
Your jQuery Best Practices
There are currently too many topics in this group that display first. To make this topic appear first, remove this option from another topic.
There was an error processing your request. Please try again.
flag
  19 messages - Collapse all  -  Translate all to Translated (View all originals)
The group you are posting to is a Usenet group. Messages posted to this group will make your email address visible to anyone on the Internet.
Your reply message has not been sent.
Your post was successful
 
From:
To:
Cc:
Followup To:
Add Cc | Add Followup-to | Edit Subject
Subject:
Validation:
For verification purposes please type the characters you see in the picture below or the numbers you hear by clicking the accessibility icon. Listen and type the numbers you hear
 
Joe  
View profile  
 More options Aug 13 2008, 11:07 am
From: Joe <joseph.is...@gmail.com>
Date: Wed, 13 Aug 2008 08:07:07 -0700 (PDT)
Local: Wed, Aug 13 2008 11:07 am
Subject: Your jQuery Best Practices
So I am working on some documentation for a project me and my team
recently completed (is it ever REALLY complete?!) and as the XHTML,
CSS, etc. standards/best practices have been hashed out, I've seen to
only come up with a few real world practices, quite frankly, because
jQuery tends to clean up/simplify a lot of prior issues with
Javascript best practices.

So, I'm requesting some info from the community.  If you have a
standard you follow for Javascript and implement it into a best
practice for jQuery, I'd be interested in hearing it.

Thanks in advance...

Joe


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Joe  
View profile  
 More options Aug 14 2008, 9:21 am
From: Joe <joseph.is...@gmail.com>
Date: Thu, 14 Aug 2008 06:21:14 -0700 (PDT)
Local: Thurs, Aug 14 2008 9:21 am
Subject: Re: Your jQuery Best Practices
Really?  No best practices?  Okay.

On Aug 13, 10:07 am, Joe <joseph.is...@gmail.com> wrote:


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Richard D. Worth  
View profile  
 More options Aug 14 2008, 9:59 am
From: "Richard D. Worth" <rdwo...@gmail.com>
Date: Thu, 14 Aug 2008 09:59:45 -0400
Local: Thurs, Aug 14 2008 9:59 am
Subject: Re: [jQuery] Re: Your jQuery Best Practices

In no particular order:
- Use the var keyword
- Cache (don't repeat) queries by throwing the result in a variable
- Chain
- Use event delegation, especially when you have lots of elements
- Write code that reads really nicely, so it doesn't need comments

- Richard


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Olivier Percebois-Garve  
View profile  
 More options Aug 14 2008, 11:18 am
From: Olivier Percebois-Garve <perceb...@gmail.com>
Date: Thu, 14 Aug 2008 17:18:44 +0200
Local: Thurs, Aug 14 2008 11:18 am
Subject: Re: [jQuery] Re: Your jQuery Best Practices

-make plugins
-use closures
-use "this"
- dom plugins return nodes so its chainable

-think with dom nodes
-be accessible (no javascript == the website is functionally usable,
google can get through )
-think about scale, i.e, w

- dont write too much doc: it gets quickly bloated, unpleasant to read
and outdated
- talk to eachother in your team so that you harmonize your ways of
thinking for naming etc


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Leanan  
View profile  
 More options Aug 14 2008, 9:34 am
From: Leanan <CrystalR...@gmail.com>
Date: Thu, 14 Aug 2008 06:34:22 -0700 (PDT)
Local: Thurs, Aug 14 2008 9:34 am
Subject: Re: Your jQuery Best Practices
I'd give it at least a week before I decided there were no best
practices.

I admit though that off the top of my head it's hard to come up with
best practices... it seems to me that jQuery just lends itself to well
structured layout, though I know you can go overboard.

I know for me I hate when chaining is done as:

$('selector').func1
                 .func2
                 .func3
                 ...etc

To me it's easier to see $('selector').func1.func2.func3

Beyond that though nothing really jumps out at me.  I'd browse through
most of the plugin's source, see how people are writing their plugins
and either a) pick what I like about what folks are doing and create
standards based on that or b) create standards based on what the
"majority" appear to be doing.

I've had to dig into plugins and modify them on a few occasions, and
some are just harder to work with than others.


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
..:: sheshnjak ::..  
View profile  
 More options Aug 14 2008, 6:34 pm
From: "..:: sheshnjak ::.." <sheshn...@gmail.com>
Date: Thu, 14 Aug 2008 15:34:00 -0700 (PDT)
Subject: Re: Your jQuery Best Practices
Well, let's go:

 - unobtrusive scripting (try to do things in a way that visitors
   with disabled JavaScript still have functional page)
 - use closures
 - have your namespace clean (all my global variables and methods
   are enclosed into jQuery.extend({...}) , so i invoke them by
   $.myCustomMethod(), or $.myGlobalVariable
 - since you are working in a team try to make chaining obvious,
   so your college doesn't miss a part (every part in new line)
 - write short and clear comments

I guess that's it, maybe you can take a peak into my js:
http://www.tomislavdekovic.iz.hr/dizajn/js.js


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
erroneousBolock  
View profile  
 More options Aug 15 2008, 7:43 am
From: erroneousBolock <erroneousBoll...@gmail.com>
Date: Fri, 15 Aug 2008 04:43:19 -0700 (PDT)
Local: Fri, Aug 15 2008 7:43 am
Subject: Re: Your jQuery Best Practices
On Aug 14, 11:34 pm, Leanan <CrystalR...@gmail.com> wrote:

> I know for me I hate when chaining is done as:

> $('selector').func1
>                  .func2
>                  .func3
>                  ...etc

I strongly disagree (with a minor modification); I do chaining as:
   $('selecector')
        .traversal
            .action1
            .action2
            .traversal
                .action3
            .end
        .end
        .traversal
            .action4
            .action5
        .end;

This lets the reader easily comprehend which subset of elements are to
be affected by nested actions.

-David


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Mike Rose  
View profile  
 More options Aug 15 2008, 12:36 pm
From: Mike Rose <MFRosengar...@gmail.com>
Date: Fri, 15 Aug 2008 09:36:29 -0700 (PDT)
Local: Fri, Aug 15 2008 12:36 pm
Subject: Re: Your jQuery Best Practices
I agree with David in that indented code yields cleaner looking and
easier to read code. My practices:

+ Each function gets a new line.
+ Each sub function indents from the above function.
+ Change the jQuery alias from $() to jq() to make sure no other
libraries interfere with my jQuery and to make the code more clear
that I am calling jQuery functions. To do this in the head of your
site before any other javascript (from jQuery) is called, simply add
this line: var jq = jQuery.noConflict();
+ NO documentation. Clean code reads fine, documentation is prone for
errors as it grows outdated and is never maintained well (in my
experience)

--
Mike

Accidentally sent this to David, sorry about that.

On Aug 15, 4:43 am, erroneousBolock <erroneousBoll...@gmail.com>
wrote:


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
h3  
View profile  
 More options Aug 15 2008, 2:00 pm
From: h3 <hainea...@gmail.com>
Date: Fri, 15 Aug 2008 11:00:17 -0700 (PDT)
Local: Fri, Aug 15 2008 2:00 pm
Subject: Re: Your jQuery Best Practices
== Encapsulation ==

One practice that isn't always used and makes you code really portable
and encapsulated:

(function($){
    // so inside here we can safely assume that $ really *is* jQuery

})(jQuery);

== Use $.extend to specify default options ==

function test(options)
    var options = $.extend({
         width: 500,
         height: 250
    }, options);

}

== Hover ==

Instead of user mouseover/mouseout, which will probably get you some
quirks anyway, use:

$('#element').hover(function(){
    // mouseover event

}, function(){

    // mouseout event

});

== CSS ==

If it can be achieved simply with CSS it probably better be CSS

== Get DOM element ==

// Bad:
$('.elements')[0];

// Good
$('.elements').get(0);

== Set/unset many styles ==

// Bad
$('#element').addClass('hello').addClass('world');

// Good
$('#element').addClass('hello world');

== Collecting ==

// Not really bad
$('#element1').addClass('hello').show()
$('#element2').show()

// Better
$('#element1').addClass('hello')
    .add('#element2').show();

I probably could list more advices but time is lacking .. sorry

On Aug 13, 11:07 am, Joe <joseph.is...@gmail.com> wrote:


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Josh Nathanson  
View profile  
 More options Aug 15 2008, 5:08 pm
From: "Josh Nathanson" <joshnathan...@gmail.com>
Date: Fri, 15 Aug 2008 14:08:50 -0700
Local: Fri, Aug 15 2008 5:08 pm
Subject: Re: [jQuery] Re: Your jQuery Best Practices

>>// Bad:
>>$('.elements')[0];

Why is that bad exactly?  Not being disagreeable, just want to know.

-- Josh


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Michael Geary  
View profile  
 More options Aug 15 2008, 5:41 pm
From: "Michael Geary" <m...@mg.to>
Date: Fri, 15 Aug 2008 14:41:03 -0700
Local: Fri, Aug 15 2008 5:41 pm
Subject: RE: [jQuery] Re: Your jQuery Best Practices
Mostly very good points, but let me comment on a couple of them...

> From: h3

> == Hover ==

> Instead of user mouseover/mouseout, which will probably get
> you some quirks anyway, use:

> $('#element').hover(function(){
>     // mouseover event
> }, function(){
>     // mouseout event
> });

It's worth noting the implementation of the .hover() method:

    hover: function(fnOver, fnOut) {
        return this.bind('mouseenter', fnOver).bind('mouseleave', fnOut);
    },

As you can see, hover does nothing more than hook up the 'mouseenter' and
'mouseleave' events to your two handlers. So, if you only need to listen for
one of these events and not both, it's perfectly OK to use one of those two
events (but not, as you note, mouseover and mouseout).

> // Bad:
> $('.elements')[0];

> // Good
> $('.elements').get(0);

I must cordially disagree. The jQuery object is specifically designed to
walk like a duck and quack like a duck. $(...)[n] is a documented and
supported feature, and it's faster than $(...).get(n) too. You're not
relying on some kind of internal implementation detail, any more than you
would be if you coded:

var a = [ 'a', 'b', 'c' ];
var x = a[0];

The only reason that .get(n) even exists is for historical backward
compatibility. In the very first version of jQuery, the $(...) return object
was not an array-like object. It had an undocumented property that contained
the array of DOM elements, and .get(n) was the only supported way to access
that array.

Very early on, we converted the code to make the jQuery object actually be
an array-like object with [0], [1], etc. properties. But since there was
already code out there using .get(n), it remained for backwards
compatibility.

> // Not really bad
> $('#element1').addClass('hello').show()
> $('#element2').show()

> // Better
> $('#element1').addClass('hello')
>     .add('#element2').show();

Now that's an interesting one. I hadn't thought of using .add() that way.
Essentially you're refactoring out the duplicate calls to .show(). Very
clever.

I'm not sure I prefer it in this simple test case, though. I think the "not
really bad" example is easier to understand. But I can see where there would
be other cases where this trick may help make the code more clear - so
thanks for pointing it out!

-Mike


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Karl Swedberg  
View profile  
 More options Aug 15 2008, 5:54 pm
From: Karl Swedberg <k...@englishrules.com>
Date: Fri, 15 Aug 2008 17:54:08 -0400
Local: Fri, Aug 15 2008 5:54 pm
Subject: Re: [jQuery] Re: Your jQuery Best Practices

On Aug 15, 2008, at 5:08 PM, Josh Nathanson wrote:

>>> // Bad:
>>> $('.elements')[0];

> Why is that bad exactly?  Not being disagreeable, just want to know.

> -- Josh

Hmm. I have no idea why that would be considered bad.

--Karl
____________
Karl Swedberg
www.englishrules.com
www.learningjquery.com


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Michael Geary  
View profile  
 More options Aug 15 2008, 7:06 pm
From: "Michael Geary" <m...@mg.to>
Date: Fri, 15 Aug 2008 16:06:26 -0700
Local: Fri, Aug 15 2008 7:06 pm
Subject: RE: [jQuery] Re: Your jQuery Best Practices

> > > // Bad:
> > > $('.elements')[0];

> > > // Good
> > > $('.elements').get(0);
> > Why is that bad exactly?  Not being disagreeable, just
> > want to know.
> Hmm. I have no idea why that would be considered bad.

I think I have some sympathy for this point of view. Consider an
object-oriented perspective where it's perferred to call an object's methods
instead of directly accessing its data, so that you have the freedom to
change the object's implementation in the future.

Indeed, jQuery gave up that bit of freedom when the underlying array was
exposed directly as [0]..[n] and .length properties on the jQuery object
itself, and documented as such. This can no longer be changed without
breaking a lot of code.

If you don't like it, blame me: I'm the one who talked John into the change
and came up with the initial patch. :-)

As to whether you should use .get(n) or [n] today, I would look at it this
way: Even if you use .get(n) in your code, that won't give jQuery the
freedom to change its implementation. jQuery will still have to support [n]
whether you use it or not. It's a done deal.

So, you may as well use the shorter and more efficient [n].

-Mike


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Karl Swedberg  
View profile  
 More options Aug 15 2008, 6:21 pm
From: Karl Swedberg <k...@englishrules.com>
Date: Fri, 15 Aug 2008 18:21:08 -0400
Local: Fri, Aug 15 2008 6:21 pm
Subject: Re: [jQuery] Re: Your jQuery Best Practices

On Aug 15, 2008, at 5:41 PM, Michael Geary wrote:

Glad you brought this up, Michael!

A couple things to note about this:

1. The .hover() wasn't always written that way internally. It was a  
change in one of the 1.2.x versions. So if you're using an old version  
of jQuery, you might want to double check for those mouseenter and  
mouseleave events before attempting to use them.

2. At this point there is no shorthand .mouseenter(fn)  
or .mouseleave(fn) like this is .mouseover(fn) and .mouseout(fn).  
Instead, we have to use .bind('mouseenter', fn)  
and .bind('mouseleave', fn)

--Karl
____________
Karl Swedberg
www.englishrules.com
www.learningjquery.com


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Michael Geary  
View profile  
 More options Aug 15 2008, 8:05 pm
From: "Michael Geary" <m...@mg.to>
Date: Fri, 15 Aug 2008 17:05:25 -0700
Local: Fri, Aug 15 2008 8:05 pm
Subject: RE: [jQuery] Re: Your jQuery Best Practices

I agree with both of you. :-)

Leanan, sure, if you have a short chain of functions, by all means put it on
one line. But if it gets complex, you may start thinking about breaking it
up into smaller chunks - and you're right, this is NOT the way to do it:

> > $('selector').func1
> >                  .func2
> >                  .func3
> >                  ...etc

What's wrong here? It's trying to line up the dots, and depending on the
font you're using, they may or may not line up. In fact, that code sample
was obviously written for a proportional font. In a real example, the code
would have been written by someone using a typical monospaced font, and the
actual spacing would be:

    $('selector').func1()
                 .func2()
                 .func3();

If you view that in a monospaced font the periods line up perfectly - but in
a proportional font it's ugly.

That's why I don't like this style: I code in a proportional font! If you
write this code in a monospaced font, it will look like that last example in
my editor. I can read it OK, but who wants to?

If you convert that to erroneous's style, it works fine in any editor,
proportional or monospaced:

    $('selector')
        .func1()
        .func2()
        .func3();

It doesn't even matter if you indent with spaces or tabs, as long as you use
them consistently. It just works.

Again, if they're short method calls just string them together on one line:

    $('selector').func1().func2().func3();

But if they're longer and you want to break it into multiple lines for
clarity, erroneous's style is the way to do it.

BTW, if you haven't coded in a proportional font, you ought to try it - if
your editor supports it. Programmer's editor support for proportional fonts
is spotty, but my favorite editor, Komodo [1], handles them fine.
Proportional fonts are great - I use Georgia on a high-density display with
ClearType enabled, so my code is more readable and I can see more of it at a
time.

-Mike

[1]: http://www.activestate.com/Products/komodo_edit/


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Michael Geary  
View profile  
 More options Aug 15 2008, 8:32 pm
From: "Michael Geary" <m...@mg.to>
Date: Fri, 15 Aug 2008 17:32:44 -0700
Local: Fri, Aug 15 2008 8:32 pm
Subject: RE: [jQuery] Re: Your jQuery Best Practices

Ah... So I could be way off base in suggesting that the mouseenter and
mouseleave events are fair game. I saw that .hover was using them and figure
it must be OK! Clearly a case of monkey see, monkey do coding. For all I
knew, they could have been intended for internal use only and subject to
change. After all, they are not documented.

So what's the intent with these two events? Are they intended for apps to
use and will remain stable - in that case they just need to be added to the
documentation.

Thanks,

-Mike


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Karl Swedberg  
View profile  
 More options Aug 15 2008, 11:38 pm
From: Karl Swedberg <k...@englishrules.com>
Date: Fri, 15 Aug 2008 23:38:28 -0400
Local: Fri, Aug 15 2008 11:38 pm
Subject: Re: [jQuery] Re: Your jQuery Best Practices

On Aug 15, 2008, at 8:32 PM, Michael Geary wrote:

Hey Mike,

I don't think you're off base. It's my impression that the two events  
are sticking around. But, then again, it's just an impression. And  
it's just mine.

They actually are in the documentation -- but they're kind of hidden:

Possible event values: blur, focus, load, resize, scroll, unload,  
click, dblclick,  mousedown, mouseup, mousemove, mouseover, mouseout,  
mouseenter, mouseleave, change, select,  submit, keydown, keypress,  
keyup, error

( http://docs.jquery.com/Events/bind#typedatafn )

They were also mentioned in the Release Notes for jQuery 1.2.2 [1].  
I'd love to see them given their own shorthand methods to put them on  
par with their mousey brethren.

Not sure, but it could be just a matter of adding them to the list  
around line 2386:

jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
        "mousedown,mouseup,mousemove,mouseover,mouseout,change,select," +
        "submit,keydown,keypress,keyup,error").split(","), function(i, name){

        // Handle event binding
        jQuery.fn[name] = function(fn){
                return fn ? this.bind(name, fn) : this.trigger(name);
        };

});

I've been meaning to mention this on the dev list, but it keeps  
slipping my mind. And I'm a little shy about suggesting such things.  
Anyway, it's always a pleasure corresponding with you. Any chance at  
all you can make it to the jQuery Conference next month? Would be  
great to meet you!

[1] http://docs.jquery.com/Release:jQuery_1.2.2#.bind.28.22mouseenter.22....

--Karl
____________
Karl Swedberg
www.englishrules.com
www.learningjquery.com


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Joe  
View profile  
 More options Aug 18 2008, 4:56 pm
From: Joe <joseph.is...@gmail.com>
Date: Mon, 18 Aug 2008 13:56:51 -0700 (PDT)
Local: Mon, Aug 18 2008 4:56 pm
Subject: Re: Your jQuery Best Practices
Wow now that's what I'm talkin about!  Well done all!  Keep'em coming,
if we haven't covered them already.

cheers.

Joe

On Aug 15, 10:38 pm, Karl Swedberg <k...@englishrules.com> wrote:


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Michael Geary  
View profile  
 More options Aug 19 2008, 8:46 pm
From: "Michael Geary" <m...@mg.to>
Date: Tue, 19 Aug 2008 17:46:31 -0700
Local: Tues, Aug 19 2008 8:46 pm
Subject: RE: [jQuery] Re: Your jQuery Best Practices

Thanks, Karl, it would be nice to meet you and some of the rest of the gang
too.

Alas, I have a high school reunion in Phoenix the same weekend. Great
timing!

-Mike

  _____  

From: Karl Swedberg

Anyway, it's always a pleasure corresponding with you. Any chance at all you
can make it to the jQuery Conference next month? Would be great to meet you!


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
End of messages
« Back to Discussions « Newer topic     Older topic »

Create a group - Google Groups - Google Home - Terms of Service - Privacy Policy
©2009 Google