10 jQuery Tips: Part1

Version 4

    1. Efficient Selectors


    Using pure JavaScript its loops and inbuilt APIs such as getElementById(), getElementsByTagName() and getElementsByClassName() are used to target elements within your HTML. These days all the major browsers support querySelectorAll(), which understands CSS query selectors and brings a very significate perfomance gain to your code.

    jQuery takes full advantage of this but you still need to be efficient with your selectors. Long chains for example are slower then shorter or more direct declarations.


    $('li[data-selected="true"] a') // Unique way to target an element but very slow
    $('li.elem a')     // Short but can be shorter
    $('#elem')     // Best Method


    In Example two you may often find you need to target an element in this way because your not able to get at the html that is rendered by BC tags or modules. This is fine as this is your only option, use parent or wrapping HTML to targert those elements.

    Where possible if you have your own HTML or where BC has a class or ID on a rendered element you should aim to target that directly.

    # over .

    # refers to a html id ( <div id="element"></div> ) and a . refers to a class ( <div class="element"></div> )

    Using an ID has greater perfomance gains over targeting with a class. Where possible you should use this selector. Since an ID is unique and you should only have one on a page there are times with multiple elements where you will need to target a class, again this is fine, you may want to do a jQuery .each()  loop on elements with a class. There is nothing wrong with that but where there is one element on the page you want to manipulate try and use an ID as the selector.


    2. Selector as an Object.


    This is another effecient faster method of using a selector multiple times within your code. For Example..


    // Set a Variable (object) as your selector
    var thisVariable = $('#navigationElement');
    // A simple Javascript loop
    for(var i=0;i<thisVariable.length;i++){
         console.log(thisVariable[i]);     // A DOM element, not a jQuery object

    Using the Variable instead of calling the selector again helps improve the perfomance of your code. As a side note, while .each() is very powerful, a traditional for loop is quicker.


    3. Console.Log()


    How do you test something is outputting correctly? You may be doing one of the following.


    1. Output it as text into an element to see the result.

    2. Alert ( alert() ) the value or variable to see what it is when you run it on your site.

    3. Prey it works or wonder why it is not working or incorect.


    The first two options are fine if your developing a website but what about if your adding aditional functionality to a live site, you do not want alert's popping up on pages as people use them as your working on some new features.


    console.log(); is a great tool and assuming you have the great firebug addon installed you can really use this to your advantage.


    console.log is an output method, it outputs what ever you like into the console which you can view and check if things are what you expect them to be. See the below for some example use cases.


    var thisVariable = $('#navigationElement').text(); // returns the text of this element, say the word is "True"
    console.log(thisVariable); // Will return the text of this element which would be "True"
    if ( thisVariable == "True" ) {
         console.log("This is true"); // You can output text to let you know that an if statement has run correctly
    console.log("This is" +thisVariable);


    4. Check if the element exists

    One of the more comon mistakes is to create a snippt of code or a function that performs an operation and then declare it to be run. This means it will run on every page even if the HTML or content you want it to run on does not exist. If you have variables that are stored based on an elements .text() or .val() for example you will also generate Javascript errors such as Null which means the element has no value and thus producing an error.
    Running that code all the time also costs you some performance.


    So what do you do?


    You check to see if the element exists first, and to do that you use the .length method. See the examples below.


    /* Example 1: Basic use example */
    // If element exists
    if ( $('#navigationElement').length ) {
         // do something
    /* Example 2, running a function if element exists */
    // Slow perfomance way
    function myFunction() {
         $('#navigationElement').text("Write this text in the element");
    // Using .length for better perfomance
    function myFunction() {
         $('#navigationElement').text("Write this text in the element");
    if ( $('#navigationElement').length ) {

    There are many other many other methods you can also use to check if an element or event meets the requirements you need to run an event. You could use jQuery selectors such as - .hasClass() for example.

    5. Create a jQuery Plugin for your code.


    I am sure many of you have used a number of jQuery plugins, some are complex, others are simple. The basics concepts of a plugin are very simple and rather then just a standard function you may want to have code you reuse often as a handy jQuery plugin instead. Please see the code below on the basic principles to achieve this.


          $.fn.yourPluginName = function(){
               // Your code goes here
               return this;


    6. Return false to prevent default behaviour


    You will most often use this in links. You may create an HTML link with ID which you wish to perform a jQuery action such as fading in another element of content for example. Links of course have a href and you may have an actual link and fetching the content through AJAX and you do not want that normal behavior to be triggered. This means you do not want the link to open a page as it would normally.

    What do you do?
    Again, it is easier to just show you an example, you can see the return false statement at the end will prevent the default action of the link.


    <a href="http://www.google.com" id="link">Click Me</a>
    $("a#link).click(function() {
         // Perform your actions
         return false; // Prevent the normal click action of the link


    7. Tell if an image has loaded?

    For either a performance reason or for a feature reason you may not want to run certain code until an image is loaded. The below code is a really simple concept to be able to know when an image has loaded.


    $('#myImage').attr('src', 'image.jpg').load(function() {  
         console.log('Image Loaded');  

    8. Test if something is hidden


    There may be times you use .hide() or .show() or .fadeOut() in your code. You may need to detect if an element is hidden or not before you run your next actions. The below snippet of code is how you do it.


    if($("#element").is(":visible") == "true") 
        //The element is Visible 

    9. $(window).load ()


    Loading your scripts on the DOM occurs when the page loads. This is great and important when you need to get script actions running as soon as possible. A lot of script or code that is not well optimised will cause the page to render slower. There are a number of scripts or say jQuery plugins you may not need to run right away. Things like tooltips, scroll events, drag events or hover events for example. You may as well load these on the $(window).load () event instead. This can be a great way to help improve your page loading.


    Note: You still will use your DOM scripting as normal for most of your work but anything not critical to be loaded ASAP can be in the $(window).load () event.



    $(window).load (function () {
         // My tooltip plugin



    10. Chaining


    It can be a suprise to see people not aware you can do this. One of the great features of jQuery is its ability to chain events etc. It really is just easy to show you the actual code, the wrong way and the write way.


    // Wrong Way
    $("element").text("This is my text");
    //The Right Way
    $("element").text("This is my text").addClass("someClass");
    /* Your chain can be contain more manipulations too */



    Please note these code examples do not consider running in compatability mode, these are only examples. Please look to implement compatability mode for jQuery on BC sites since Many aspects of BC use Prototype which will cause conflicts.