Eight Tips That Makes You a Better jQuery Coder

27 comments so far | Add yours Digg del.icio.us

jQuery is a javascript framework that is becomming insanely popular. It is fast, easy to use and creating custom plugins and components is done in a breeze. These days, everyone is a jQuery developer and the plugin repository over at jquery is virtually exploding with new plugins being added every day.

In light of all this, here are my eight best tips for becomming a better jQuery coder that you might consider before taking on your next project.

1. Stay accessible and maintain degradability

With jQuery being as popular as it is, more and more people are writing plugins and creating component packages that are ready to use as-is. But few developers bare in mind that it should also work without javascript turned on. Well, thats one of the main reasons to go unobtrusive, right? So as an example, this code:

CSS:
.animate{color:red;display:none};

jQuery:
$('.animate').fadeIn();

…would use jQuery to fade in the elements that has the class name ‘animate’. But if javascript is turned off, the browser still parses the CSS and will naturally hide the elements without ever showing them!

Instead, always make a habit of separating “javascript CSS” and “pure CSS”. Try this:

CSS:
.animate{color:red}
.animate_js{display:none};

jQuery:
$('.animate').addClass('animate_js').fadeIn();

This way, you can style the elements for each scenario and maintain degradability in a sensible way. As always, test your code without javascript turned on before deployment.

2. Move visual effects to the presentational layer

When writing javascript, always focus on behaviour. jQuery is not CSS, and be aware of the core differences between presentation and behaviour. For example, it is often a good idea to add classes instead of pure CSS properties. Avoid fades and glamour inside the functions. Save the effects for a juicy demo but stay low key in the javascript functions - everyone doesn’t share your visual taste!

3. Use firebug and the console.log

Firebug is your friend when developing with jQuery. And so is the console.log command that gracefully replaces the annoying alert(). Simply type console.log() to debug whenever you need to in your code. But remember to remove them before production since many browsers will choke on them, including IE (of course).

4. Define sensible defaults and use a limited amounts of parameters

When you get bitten by the jQuery bug and start to create plugins, you are often tempted to maximize the number of parameters to make it as flexible as possible. This is all very noble, but stay clear and try not to confuse the web developer with tiny parameters that hardly make any difference (like fade speeds etc). Instead, pass on a parameter object and define sensible defaults. Your code is not meant to be everything under the sky!

5. Encapsulate your custom alias

jQuery is not the only framework that uses the $ dollar shorthand. Many jQuery plugins and code snippets uses the $ exclusively for defining onDomReady callbacks and CSS selector functions, but you might end up with cross-framework conflicts by doing so.

Instead you can use a custom alias, (which can still be $) like this:

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

The example above uses both the shortcut for $(document).ready() and the argument to write failsafe jQuery code using the $ alias, without relying on the global alias. You can and should also encapsulate the $ when authoring plugins, like this:

(function($) {
  // plugin code here, use $ as much as you like
})(jQuery);

6. Define custom callbacks

When authoring jQuery plugins, it’s a good idea to let the developer assign custom callbacks as parameter functions, thus making it possible to customize the plugin even more. So instead of forcing callback effects inside the plugin, trigger event functions and set the effects free.

Here is an example where we pass on the onFade function to the plugin, written as a simple fadeIn plugin:


/*
This plugin fades an element and triggers the onFade when completed

EXAMPLE USAGE:
  $('.fademe').customFade({
    fadeSpeed: 50,
    onFade: function(elem) {
      console.log(elem+' has faded!')
    }
  });
*/

jQuery.fn.customFade($params) {
  var $defaults = {
    fadeSpeed: 1000,
    onFade: function(element){}
  };
  var $p = $.extend($defaults, $params);
  $(this).fadeIn($p.fadeSpeed,$p.onFade($(this)));
}

7. Be aware of browser differences

jQuery is very cross-browser friendly. But there are still glitches, especially with browsers like Safari who has a different onLoad trigger, and of course MSIE. Always test in several browsers once in a while and pay close attention to when and where the glitches occur.

8. Don’t overuse it and define your purpose

Make sure you are not using jQuery just because you can. Always analyze your needs and have a clear idea of what you want to achieve and why before even writing the first line. Sketch your code visually and discuss your ideas with fellow peers before coding. Don’t re-invent the wheel unless you are doing it to educate yourself, have a look around for high quality plugins (cough, DevKick, cough) for inspiration and to see what has alreay been done.

Happy coding!

27 Responses so far. Add yours.

Permanent link At 11:22 pm on March 20th, 2008 , Marko wrote:

Wow thanks for the article, diggin into it now!

Permanent link At 2:03 pm on April 1st, 2008 , Garry wrote:

A useful set of tips. I’m still in the early (ish) stages of using jquery so all these little bits of info are great. Keep them coming!

Permanent link At 5:15 pm on April 10th, 2008 , Maniquí wrote:

Although I’m not a jQuery Coder, we use it as our primary JS library here at work. I have very basic programming knowledge, but I find it easy to implement and use jQuery and its plug-ins. There are good tips here (we already follow some of them).
Regarding the first tip, an easier (or maybe, cleaner, I think) but similar way to stay accessible and maintain degradability is by adding (using jQuery, of course) a class="js" to the body. That way, you can create/maintain specific CSS classes that will work when JS is enabled.
I mean, it’s almost exactly the same approach you suggest, but this way, you can use the same classes and create JS specific CSS rules by just adding .js in front.

Thanks for this article.

Permanent link At 11:54 am on April 11th, 2008 , David (author) wrote:

@Maniquí: that’s not a bad idea at all! great tip. all it takes is a $(’body’).addClass(’js’);

Permanent link At 8:25 pm on April 11th, 2008 , Maniquí wrote:

Glad you like it. Yes, that’s exactly the code we use. I forgot to post it here.

Permanent link At 6:47 pm on April 19th, 2008 , konteyner wrote:

thank you very much

Permanent link At 10:06 pm on May 3rd, 2008 , :-: S€zæR ->> wrote:

CSS “Cascading Style Sheets” LessoNs - WeB DesigN LessoN - - Web site : http://WWW.css-lessons.ucoz.com/index.html

Permanent link At 1:08 pm on May 13th, 2008 , hekim group wrote:

That way, you can create/maintain specific CSS classes that will work when JS is enabled. thank you.

Permanent link At 4:35 pm on June 16th, 2008 , kabin wrote:

The use jQuery and its plug-ins. There are good tips here

Permanent link At 5:39 pm on October 16th, 2008 , fibercement wrote:

thanks a lot.

Permanent link At 5:40 pm on October 16th, 2008 , hekimboard wrote:

Thanks hekim group.Good idea.

Permanent link At 1:02 pm on March 11th, 2009 , halı yıkama makinası wrote:

thank site very much

Permanent link At 1:03 pm on March 11th, 2009 , deniz iskelesi wrote:

good site

Permanent link At 1:04 pm on March 11th, 2009 , halı yıkama makinaları wrote:

halı yıkma makinası, halı yıkama makinaları, HALI YIKMA MAKİNASI, HALI YIKAMA MAKİNALARI

Permanent link At 1:04 pm on March 11th, 2009 , vesaire hikayeleri wrote:

good nice post bautiful

12 Trackbacks & Pings:

Permanent link Trackback at 8:43 pm on April 3rd, 2008 by jQuery tips, migrating from jQuery’s tablesorter to Ext JS’ GridPanel | Norm's blog:

[…] ran across this post which has some good jQuery […]

Permanent link Trackback at 4:58 am on June 30th, 2008 by Información de Tecnologías»Archivo del blog » Siguiendo con jQuery:

[…] 2) 8 tips para ser un mejor programador con jQuery: http://monc.se/kitchen/150/eight-tips-that-makes-you-a-better-jquery-coder […]

Permanent link Trackback at 3:15 am on March 20th, 2009 by Daily Links | AndySowards.com :: Professional Web Design, Development, Programming, Hacks, Downloads, Math and being a Web 2.0 Hipster?:

[…] Eight Tips That Makes You a Better jQuery Coder | David’s kitchen Great jQuery coding STREAMLINING tips (tags: design programming webdesign javascript 8 howto webdev jquery ajax coding web development) […]

Permanent link Trackback at 6:17 pm on March 20th, 2009 by 86 jQuery Resources To Spice Up Your Website | Hi, I'm Grace Smith:

[…] 8 Tips That Makes You a Better jQuery Coder […]

Permanent link Trackback at 10:03 am on June 20th, 2009 by Fotografia Ślubna Dąbrowa Gónicza:

Fotografia Ślubna Dąbrowa Gónicza…

I like Yours post. If You have time, come and visit our’s site….

Permanent link Trackback at 1:23 pm on August 11th, 2009 by Twitted by davidbigg:

[…] This post was Twitted by davidbigg […]

Permanent link Trackback at 9:19 am on August 30th, 2009 by Eight Tips That Makes You a Better jQuery Coder | David’s kitchen:

[…] The rest is here: Eight Tips That Makes You a Better jQuery Coder | David’s kitchen […]

Permanent link Trackback at 1:56 pm on November 21st, 2009 by jquery interactive picture | WebDesignExpert.Me:

[…] Eight tips to make you better jQuery coder – Link. […]

Permanent link Trackback at 3:33 am on December 13th, 2009 by Internet Arrow » Eight Tips That Make Your a Better jQuery Coder:

[…] Wordpress (4) Eight Tips That Make Your a Better jQuery Coder READ MORE […]

Permanent link Trackback at 7:19 pm on January 12th, 2010 by 8 dicas para fazer códigos melhores com jQuery | desenvolvimento para web:

[…] de começar seu próximo projeto. Este é um artigo traduzido do original “Eight Tips That Makes You a Better jQuery“, do blog David’s Kitchen, e sofreu pequenas […]

Permanent link Trackback at 2:46 pm on June 26th, 2010 by design web:

design web…

Creative Web Media vous propose la réalisation de votre site internet vitrine qui vous garantira une parfaite présence sur la toile, une totale garantie de crédibilité auprès de vos clients, et un référencement efficace auprès des principaux mo…

Permanent link Trackback at 5:31 pm on August 7th, 2010 by Eight Tips That Makes you a Better jQuery coder « Nguyen Xuan Huy:

[…] from: http://monc.se/kitchen/150/eight-tips-that-makes-you-a-better-jquery-coder Tags: jquery tips Share this post! Twitter Digg Facebook Delicious StumbleUpon Google […]

This entry was posted on Thursday, March 20th, 2008.

React

Categories

RSS Feeds

Bookmark

Translate

Both comments and pings are currently closed.