Synopsis

Adopt a restrained and consistent approach to implementing animation functionality.

Description

jQuery provides some basic functionality, the simplest of which is demonstrated by the following code:
    $("#MyDiv").hide("slow");

Here, the hiding of MyDiv is animated.

It is important that a consistent approach to the use of effects and anuimation is adopted across the web application.

There is a temptation when discovering this functionality to ‘go nuts’ and have divs whizzing in from all angles with buttons flashing and all hell breaking loose. In general you should try to show restraint when using animation.

If possible, feed animation use into UI standards.

jQuery Coding Standards Menu

  1. jQuery Variables
  2. DOM Manipulation
  3. Events
  4. Page Style and Layout Changes
  5. Effects and Animation
  6. Selectors
  7. Plugins
  8. Chaining
, ,

Synopsis

Avoid making changes to individual CSS styles using the jQuery API functions.

Use CSS Classes intead.

Description

Avoid using direct CSS style changes (using .css() ), and inbuilt style functions .length(), .width(), etc.

Instead, declare the styles in a class within a CSS StyleSheet file (not inline within an HTML file!), and use .addClass(), .removeClass() or .toggleClass() upon your selecteded object(s).

For example, avoid this type of declaration:

    $("#MyTR").css({
       "background-color":"gray"
    });

Use instead:

    $("#MyTR").addClass("HighlightRow");

    /*In CSS File:*/
    .HighlightRow
    {
       background-color:gray;
    }

This promotes correct separation of content and style.

Embedding style changes in JavaScript/jQuery has the following implications when it comes to rebranding or changing a site’s theme:

  • It is less likely that a consistent approach has been adopted with regard to styling making the task harder.
  • A bigger and more complex  impact analysis required to identify files that require changed.
  • More files require changed.
  • More files = more testing. As we will be changing JavaScript code, we will have to retest more than we otherwise would have.

A discussion on the merits of Behavioral Separation is outside the scope of this article. It may seem a little draconian to advise against using .css() and other style-change functions, but is essential when attempting to achieve this goal.

jQuery Coding Standards Menu

  1. jQuery Variables
  2. DOM Manipulation
  3. Events
  4. Page Style and Layout Changes
  5. Effects and Animation
  6. Selectors
  7. Plugins
  8. Chaining
, ,

Synopsis

1. Adopt a consistent approach when writing document ready events.

2. Use a document ready event in place of window onload.

3. No JavaScript or behavioural markup is to be included in HTML files.

4. Events must be late-bound within the $(document).ready()handler code itself.

5. Use the shorthand event syntax.

6. Anonymous function handlers must be limited to one line of code.

Document Ready Declaration

1. The handler for the document ready event must be an anonymous declared in the following form:

    $(document).ready(function(){
    	//all initialization
    });

This is clear, readable, and should be used ahead of other possible invocations of this functionality, which include:

    $(handler);
    $().ready(handler); //not recommended
    $(document).bind("ready", handler); //not fired if bound after document ready fires

(And, of course, ‘$’ is interchangeable with ‘jQuery’)

This standard stipulates the use of the given format, however the important aspect of this is the recommendation to adopt a consistent approach to writing document ready events.

2. A Document Ready handler must be specified in place of the window.onload event, except in the rare event where this is too soon: http://blog.arc90.com/2008/05/16/a-jquery-tip-dont-use-jquery/

Note: There is no limit on the number of document ready handlers that can be associated with a page. Event handlers are added to a stack that will be executed when the document is ready.

Binding and Behavioural Markup


3. No JavaScript or behavioural markup is to be included in HTML files. For example, the red-highlighted code should not be present in HTML any more:

    <input type="button" id="MyButton" onclick="OnClickMyButton()">

4. Events must be late-bound within the $(document).ready()handler code itself. For example:

    $(document).ready(function(){
        $("#MyButton").click(MyFunc);
    });

    function MyFunc(event){
    }

5. Use the shorthand event syntax:

    $("#MyButton").click(MyFunc); //use this
    $("#MyButton").bind("click", MyFunc); //instead of this

Event Handlers and Anonymous Functions
6. jQuery allows developers to specify anonymous functions for event handlers. For example:

    $("#MyButton").click(function(){//code});

However, to avoid On Ready Bloating (a side effect of late-binding where the document.ready() function handler becomes large, cumbersome, and unmaintainable), these anonymous function handlers must be limited to one line of code:

    $("#MyButton").click(function(){
        MyFunction();
    });

If we need to refer to the this object, we wrap it in a jQuery object, and pass it within our anonymous function (it is better practice to wrap in a jQuery object early on):

    $("#MyButton").click(function(){
        MyFunction($(this));
    });

jQuery will automatically pass the event object when calling our anonymous function. We can access it as follows:

    $("#MyButton").click(function(event){
        MyFunction($(this), event);
    });

Incidentally, the declaration for MyFunction for the above example would be:

    function MyFunction($this, event){
        //code
    }

As well as avoiding OnReady Bloating, this approach makes our code easier to debug and more readable.

jQuery Coding Standards Menu

  1. jQuery Variables
  2. DOM Manipulation
  3. Events
  4. Page Style and Layout Changes
  5. Effects and Animation
  6. Selectors
  7. Plugins
  8. Chaining
, ,

Synopsis

Manipulation of the Document Object Model (DOM) can be costly and inefficient, regardless of whether it is undertaken through jQuery or JavaScript.

The API provided by jQuery facilitates greater DOM manipulation, possibility outwith of the awareness of the developer.

Therefore, you should limit the amount of code that performs DOM Manipulation tasks.

Description

The challenge here is to recognise:

  1. When DOM Manipulation is being undertaken
  2. When it is being done in excess.

Both of these are open to interpretation as it is difficult to stipulate exactly what constitutes excessive DOM manipulation.

In general, very little DOM manipulation should really be undertaken. You should be hitting the DOM in this way only when is absolutely necessary.

Let us examine the following example:

var $myList = $("#myList");   

for (i=0; i<1000; i++){
    $myList.append("This is list item " + i);
}

This code adds 1000 lines to an HTML list. This is done with 1000 successive calls to the .append() method, and hence, 1000 manipulations to the DOM.

The following code, modified from the example above demonstrates how this can be made more efficient:

var $myList = $("#myList");
var li = "";   

for (i=0; i<1000; i++){
    li += "<li>This is list item " + i + "</li>";
}  

$myList.append(li);

In this example, the HTML is constructed in advance. The HTML is appended in one call, greatly reducing the amount of manipulation you undertake.

jQuery Coding Standards Menu

  1. jQuery Variables
  2. DOM Manipulation
  3. Events
  4. Page Style and Layout Changes
  5. Effects and Animation
  6. Selectors
  7. Plugins
  8. Chaining
, ,

Synopsys

All variables that are use to store/cache jQuery objects should have a name prefixed with a ‘$’.

Consider using chains in place of jQuery object variables.

Description

There is often a requirement to store/cache a jQuery selection in a holding variable. Where this is the case, you should prefix the variable name with a ‘$’.

For example:

    var $MyTable = $("#MyTable");
    $MyTable.addClass("MyTable");
    $MyTable.append("<tr></tr>");

Also, in conjunction with $(this):

    var $this = $(this);

Storing in a holding variable helps reduce the number of calls into jQuery, and enhances performance. The dollar notation on all jQuery-related variables helps us easily distinguish jQuery variables from standard JavaScript variables at a glance (e.g. string, integer, etc).

Cached Variables vs Chains

The above example could have been written efficiently as a chain like so:

    $("#MyTable").addClass("MyTable").append("<tr></tr>");

This has the advantage in removing the need for a cached variable, and in this particular case makes sense.

When chains become long, complex and especially hard to read, you should split them up, storing intermediate selections in a holding variable: http://stackoverflow.com/questions/1286829/is-there-a-preferred-way-of-formatting-jquery-chains-to-make-them-more-readable

This does not result in much (if any) of a performance hit. Objects are held as references, not values, so their impact is minimal: http://stackoverflow.com/questions/1287106/can-it-be-disadvantageous-to-store-jquery-objects-in-a-variable

The Chaining Standards cover this in more detail.

jQuery Coding Standards Menu

  1. jQuery Variables
  2. DOM Manipulation
  3. Events
  4. Page Style and Layout Changes
  5. Effects and Animation
  6. Selectors
  7. Plugins
  8. Chaining
, ,

Yes, maybe, and yet, a few days ago I code reviewed a bit of code like this:

$("select[id='MySelect']").val(1);

Where, of course, an ID selector would have sufficed, and would have been faster, smaller and better:

$("#MySelect").val(1);

jQuery isn’t a silver bullet against bad code. You can still write some quite horrific jQuery, and moreover, as JavaScript isn’t subject to precompilation you can ship syntactically incorrect jQuery.

If this were not enough, jQuery, and in particular the Sizzle Selector Engine does a lot ‘under the hood’ with regard to DOM manipulation and traversal. The consequence of this is that, although you code may look great, and be perfectly bug free, it may grind to a painful halt under real-world stupid-user scrutiny.

Standards can help guard against all of this. I’m not really wanting to get tried up in a discussion on the virtues of standards, but, in general, if you believe in them elsewhere, then they are equally valid here.

jQuery Coding Standards Menu

  1. jQuery Variables
  2. DOM Manipulation
  3. Events
  4. Page Style and Layout Changes
  5. Effects and Animation
  6. Selectors
  7. Plugins
  8. Chaining
, ,

Overview

The jQuery JavaScript library has established itself as the most dominant and widely-used JavaScript library available.

And yet, for me, there no sites that appear to pull together best practices for jQuery development in a way that Douglas Crockford has done with his JavaScript Code Conventions.

So, while researching the language for the rollout of a jQuery course, I found myself needing to develop a set of standards.

Some time on from this, lessons have been learned and I feel I have a good workable set of jQuery standards. I have decided to present these in a series of posts that fall under the following headers:

  1. jQuery Variables
  2. DOM Manipulation
  3. Events
  4. Page Style and Layout Changes
  5. Effects and Animation
  6. Selectors
  7. Plugins
  8. Chaining

Scope

The initial scope of these posts is intended to cover coding from the core jQuery library. only. It is not intended to cover the use of jQuery UI, or other high-profile plugins.

Such is the significance and widespread adoption of some of these add-ons, for example the  jQuery forms validator, or anything that malsup has written,  that a set of good practice guidelines for these may also be of benefit. But not here, not now at least.

Audience

These standards were developed following the rollout of jQuery within a corporate development community.

They were a result of capturing developer experiences, and evolved over a number of iterations to suit the ecosystem of a very specific development community.

I do believe, however, that they have a broad relevance and use, and will serve any jQuery developer well.

jQuery Version

These standards were developed against jQuery 1.4.2.

I Don’t Think jQuery Should / Needs To be constrained

I disagree, which is why I’ve written these standards. I’ve felt this warrants a separate article.

I think you/a standard/everything here is wrong

And you may be correct.

I’m happy to change, debate and listen to any opinions to this end, but I would encourage you to bear in mind the audience, and motivation for this. The standards were developed for use within a corporate programming environment, and although I’ve always tried to carry these into my everyday programming adventures, I realise they are not for everyone.

For me, standards are there to make you think about what you are doing. On occasions I think standards can be broken, but these scenarios will be exceptions, not rules. And if you are thinking about deviating from a standards, so you should be thinking about commenting. For a well disciplined programmer, good standards lead to better code and better comments.

You may also feel that I’ve missed something. Quite possibly – this was evolved over a number of months in response the practices adopted by a specific development community. I hope for these standards to evolve now they have been exposed to the outside world!

, ,

For me, one of the best, yet under-utilised features of jQuery is the custom selector.

Custom selectors are another way to extend jQuery for your own means, and to hive off worker functionality that needn’t clutter your code.

The Old Way

To demonstrate this, I’m going to use a simple example for identifying elements with empty value attributes. Consider the scenario where you want a bit of client-side script to alert you if there are any empty textboxes upon form submission:

var i = 0;
$("input:text").each(function() {
    if ($(this).val() === "") {
        i++;
    }
});

if (i > 0) {
    alert("Not all fields filled out");
}

Now, at face-value then this is a quite valid way of doing things. However, for me, this is a worker task – a task that in theory can be hived away elsewhere so as not to clutter your code. We can of course, make it into a function:

function HasEmpty(selector)
    var i = 0;
    $("input:text").each(function() {
        if ($(this).val() === "") {
            i++;
        }
    });
    return (i > 0);
}

But this really isn’t all that flexible. Do you want to return the count of items? Or just a Boolean indicating if any are empty? And it’s not really all that jQuery-like.

The New Way

So, how can we make this a little more elegant? By using custom selectors, of course. In fact, we will just be reusing a language feature of jQuery that jQuery itself uses.

Have you ever wondered how jQuery implements the CSS Pseudo-Class Selectors such as :first-child or :hidden, etc? Well, under the hood, these are all really just custom selectors built into the jQuery framework. This goes for all of the 30+ Pseudo-Class selectors in jQuery.

To do this, we make use of the little known property jQuery.expr[':'] in conjunction with jQuery.extend like so:

$.extend($.expr[":"], {selectorName:[anonymous function]});

The interesting part of this is [anonymous function]. This function will be called for every element against which this selector runs (much in the same way that .each works).

If the function returns true” then the current element will be included in the result set. Conversely, a return value of false  false” will exclude it. This function is only really useful if we can reference each object upon which it works. We can use this by using the basic definition of this function (there is an extended one which we will discuss later). This accepts a DOM object representing the current element as a parameter.

When referring to the jQuery core, we see that it adopts the convention of naming the parameter elem:

enabled: function(elem){
    return elem.disabled === false && elem.type !== "hidden";
},

disabled: function(elem){
    return elem.disabled === true;
},

Who are we to argue? So now, our Custom Selector template becomes:

 $.extend($.expr[":"], {
    selectorName:function(elem){
        return [boolean expression];
    }
});

So, returning to our original example of wanting to search for all elements with an empty val attribute, our code takes on the following form.

$.extend($.expr[':'], {
    valueEmpty: function(elem) {
        var $elem= $(elem);
        return ($elem.val() === "") && ($elem.attr("type") === "text");
    }
});

I’ve added a check to ensure the DOM element is a text box, and I’ve cached the jQuery cast of elem to avoid multiple calls into the library. Really, the implementation is secondary to the discussion here. The important thing to note is that it will return a Boolean. Calling out new code is trivial, and as we would expect:

alert($(":valueEmpty").length);

Although, I always advocate combining low-performance selectors (of which this is one) with higher performance ones (more on this later):

alert($("input:valueEmpty").length);

Parameterised Custom Selectors

You’ll notice that some Pseudo-Class selectors accept a parameter, for example :has(selector). So how do we get some of that good stuff? We are going to build a lengthBetween selector that will filter out items whose length is greater than two specified parameters, in this case, four and eight. The calling code will look like:

alert($("input:lengthBetween(4,8)").length);

The anonymous function we specified for our original custom selector actually has four parameters. We only used the first, elem. The following is the full definition:

$.extend($.expr[":"], {selectorName:function(elem, i, match, array){
    return [boolean expression];
});

So what are all of these parameters?

  • elem we are already familiar with - it is the current DOM element of the iteration stack
  • i is the index of elem upon the stack
  • match is an array that contains all information about the custom selector
  • array contains all the elements in the stack over which we are iterating

We are interested in the match array parameter, as this is where we will retrieve parameter information. The match array stores four pieces of information. So, given the the selector call:

alert($("input:lengthBetween(4,8)").length);
  • match[0] – contains the full pseudo-class selector call. In this example :lengthBetween(4,8)
  • match[1] – contains the selector name only. In this example lengthBetween
  • match[2] – denotes which, if any, type of quotes are used in the parameter expression. i.e. single (‘)  or double (“). In this example it will be empty.
  • match[3] – gives us the parameters, i.e. what is contained in the brackets. In this example 4,8

So, if we just want the parameters, then match[3] is the way forward. This is a simple string value and it’s really up to you how you handle it. You can String.Split() it to get multiple parameters, and you can consider validating the parameters somehow. Again, we are drifting away somewhat from the scope of this discussion, so I’ll refer to the jQuery core once more:

gt: function(elem, i, match){
    return i > match[3] - 0;
},

Here, a single parameter is expected and assumed. No validation attempt is made. So, returning to our :lengthBetween selector, the implementation might look something like:

$.extend($.expr[":"], {
    lengthBetween: function(elem, i, match) {
        var params = match[3].split(",");  //split our parameter string by commas
        var elemLen = $(elem).val().length;   //cache current element length 
        return ((elemLen >= params[0] - 0) && (elemLen <= params[1] - 0));  //perform our check
    }
});

So there we have it - A custom selector that will filter out values whose length is between one and three characters.

Speed and Efficiency

I have always encouraged developers to consider the speed and efficiency of their basic selectors. Although it is not an exact science (relative speeds can differ between browsers, and selector combinations can be unpredictable), I have always advocated the following rule of thumb when it comes to using your selectors:

  1. An #ID selector is quicker than element selector is quicker than .class selector.
  2. Always try to prefix .class selectors with an element selector
  3. #ID selectors almost always can be used in isolation.

For further reading, Hugo Vidal Teixeira has provided a nice analysis of jQuery selector performance.

So where do pseudo-class and custom selectors fit into this?

An #ID and element selector map directly to the core JavaScript functions .getElementById() and .getElementsByTagName().

Class, Pseudo-Class and Custom selectors all require a scan of the DOM to filter out elements, which is inherently slow. So, treat custom selectors like class Class and Pseudo-Class selectors when it comes to performance.

Resources / Further Reading

Some useful links for further reading and other custom selectors.

And Finally…

What of jQuery.expr[':']? The eagle eyed among you might have questioned as to why we should be constrained to just overriding the colon? In my opinion, this is straying into dangerous territory, however it is possible given the versatility of the Sizzle selector engine.

You can read more in this article, which documents how to override the ‘<’ symbol.

,