Loving jQuery

In recent weeks I have come to love jQuery. jQuery is this lightweight, elegant and so-much-fun-to-code-with JavaScript library. You may already have it in your source code if you’re using either the latest version of WordPress or Drupal.

jQuery is so easy to get to grips with, the documentation is simple to follow and complete with loads of code samples.

jQuery’s elegance comes in the form of its ability to select DOM nodes through CSS-like syntax (i.e., CSS queries) in a compact way—brilliant for those who are already very familiar with CSS!

Most or even all actions start with a CSS query, which in a sense promotes the use of unobtrusive JavaScript as it’s simply easier to use the $() syntax than add a function directly into HTML.

jQuery is also very much down to earth in a practical way providing a few neat toggle functions:

  • toggle — show/hide selected elements
  • slideToggle — show/hide selected elements with slide Up/Down effects
  • toggleClass — add/remove a class from selected elements

There are also some handy plugins such as the Flash plugin and the ifixpng plugin, which fixes PNG transparency for img elements and CSS backgrounds in IE.5 and IE6.

If something isn’t built-in, extending jQuery is ridiculously easy via custom plugins. Here’s one way you could define a custom plugin:

jQuery.fn.myPlugin = function() {
    // Your plugin code goes in here

To take advantage of jQuery’s chainability you need only add a single line returning the current context object—this:

jQuery.fn.myPlugin = function() {
    // Your plugin code goes in here
    return this;

To demonstrate how easy jQuery is to extend I created a simple one line plugin to toggle fadeIn and fadeOut effects, see below.

jQuery fadeToggle plugin:

jQuery.fn.fadeToggle = function(s, fn){
    return (this.is(":visible"))
        ? this.fadeOut(s, fn)
        : this.fadeIn(s, fn);

Example usage:


A demo of jQuery fadeToggle plugin in action