Tutorial jQuery 001

download Tutorial jQuery 001

of 24

Transcript of Tutorial jQuery 001

  • 7/28/2019 Tutorial jQuery 001

    1/24

    33 Jquery tips

    This article is mostly aimed at people who are just starting to learn jQuery. I assume you know thefollowing:

    Base knowledge of JavaScript What jQuery is

    How to include jQuery in a web page

    Basic knowledge of how to use the $ function (for example: $(#test .testing))

    Basic understanding of the chainable events

    Know what $(document).ready(function () { }); does(sometimes seen as $(function () {} ); or $().ready(function() {});)

    Know intermediate HTML and CSS (lists, padding, colors, borders and margin)

    If you dont know anything about how to use jQuery you should readthis. This is not meant to be anintroduction to jQuery. This is meant for people who have tried jQuery and may have been frustratedbecause they werent sure how to do something correctly.

    Table of Contents

    1. Objects and Methods2. Jquery is Chainable3: jQuery can Behave Somewhat like an Array4: jQuery in a Variable5: Keep Animations from Building Up6: What Does callback Mean7: Do Something when any AJAX Starts/Ends8. Load the framework from Google Code

    9. Use a cheat sheet10. Combine all your scripts and minify them11. Use Firebug's console logging facilities12. Keep selection to a minimum by caching13. Keep DOM manipulation to a minimum14. Wrap to single element doing DOM insertion15. Use IDs instead of classes wherever possible16. Give selectors a context

    17. Use chaining properly18. Animate properly19. Event delegation20. Use classes to store state21. Use jQuery's data() method to store state22. Write your own selectors23. Streamline HTML, modify after page load24. Load content for speed and SEO benefits

    25. Use jQuery's utility functions26. Use noconflict to rename jquery object27. How to tell when images have loaded28. Always use the latest version29. How to check if an element exists30. Add a JS class to your HTML attribute31. Return 'false' to prevent default behaviour32. Shorthand for the ready event

    Pg 1 of 24

    http://docs.jquery.com/Tutorials:How_jQuery_Workshttp://docs.jquery.com/Tutorials:How_jQuery_Workshttp://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip1%23tip1http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip2%23tip2http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip2%23tip2http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip3%23tip3http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip4%23tip4http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip5%23tip5http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip6%23tip6http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip7%23tip7http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip8%23tip8http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip9%23tip9http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip10%23tip10http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip11%23tip11http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip12%23tip12http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip13%23tip13http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip14%23tip14http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip15%23tip15http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip16%23tip16http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip17%23tip17http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip18%23tip18http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip19%23tip19http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip20%23tip20http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip21%23tip21http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip22%23tip22http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip23%23tip23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip24%23tip24http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip25%23tip25http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip1%23tip1http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip2%23tip2http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip3%23tip3http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip4%23tip4http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip5%23tip5http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip6%23tip6http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip7%23tip7http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip8%23tip8http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip9%23tip9http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip10%23tip10http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip11%23tip11http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip12%23tip12http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip13%23tip13http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip14%23tip14http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip15%23tip15http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip16%23tip16http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip17%23tip17http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip18%23tip18http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip19%23tip19http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip20%23tip20http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip21%23tip21http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip22%23tip22http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip23%23tip23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip24%23tip24http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip25%23tip25http://docs.jquery.com/Tutorials:How_jQuery_Works
  • 7/28/2019 Tutorial jQuery 001

    2/24

    1. Objects and Methods

    Objects work so well because they act just like real life objects- objects have properties and methods.So if we were talking about a lamp, a property of it may be its height or width, say 12cm. A method ofit may be to shine (an action). And when its shining, its brightness property would be of a greatervalue than when it wasnt.

    By being able to tie, essentially, sub-variables to variables you dont have to worry if that variable isalready used. A method is a function that is specific to an object. For example, the jQuery methodheight (written as .height()) is a method of the jQuery object.

    Use the following code as an example:

    vartestText = $('div#test').text();

    This sets the value of the variable testText with the text of the div with the id of test; prettystraightforward.

    The jQuery function, $, returns an object that contains all the elements that match the given

    CSS selector(s) (in this case div#test). This object has access to all of the methods mentioned in thejQuery documentation. text is a method that returns [the] combined text contents of all matchedelements. (fromhere).

    2. Jquery is Chainable

    JavaScript is chainable. Chainable means you can have multiple methods joined together. Forexample this jQuery:

    var testText = $('div#test').parent().text();

    and this HTML:

    This is the content!

    That code would return the text of the parent of the div with the id of test. The parent methodreturned a new jQuery object containing the elements parent.

    Not all things are chainable. For example the text method doesnt return a jQuery object, itreturns a string. You use the parent method on a string, because that doesnt make any sense at all.However, because it returns a string you can use all the methods that you can use with astring. These methods are documented very wellhere. For example, it is perfectly fine to use the splitmethod on the text method, as demonstrated here:

    var testText = $('div#test').parent().text().split(' ');

    Now the variable testText would be set as an array that contains This,'is,'the, and content! as itemsin the array.

    3: jQuery can Behave Somewhat like an Array

    In JavaScript you access the first item in an array like this: arrayVariable[0]. You find how manyitems are in an array using arrayVariable.length. You can do the same with jQuery. Each object thatmatches the specified selectors is an item in the array. Look at this:

    Pg 2 of 24

    http://docs.jquery.com/http://docs.jquery.com/http://docs.jquery.com/Attributes/texthttp://docs.jquery.com/Attributes/texthttp://www.w3schools.com/jsref/jsref_obj_string.asphttp://www.w3schools.com/jsref/jsref_obj_string.asphttp://www.w3schools.com/jsref/jsref_split.asphttp://docs.jquery.com/http://docs.jquery.com/Attributes/texthttp://www.w3schools.com/jsref/jsref_obj_string.asphttp://www.w3schools.com/jsref/jsref_split.asp
  • 7/28/2019 Tutorial jQuery 001

    3/24

    /*Assume the HTML looks like this:

    Content #1!Content #2!Content #3!Content #4!

    Content2 #1!*/

    // returns 4$('#wrapper .box').length;

    // num is equal to 4varnum = $('#wrapper .box');num = num.length;

    // text is equal to 'Content #2!'

    vartext = $("#wrapper .box")[1];

    // text is equal to 'Content #1'vartext = $("#wrapper .box")[0];

    // text is equal to 'Content2 #1'vartext = $("#wrapper2 .box")[0];

    4: jQuery in a Variable

    You can store the results from a jQuery selection in a variable, and still access all the same methods.It is good practice to prepend the variable with $ to remember that you are, indeed, working with a

    jQuery object. Example:

    var$testBox = $('#test');// the variable testHTML is equal to the content's of '#test'vartestHTML = $testBox.html();

    5: Keep Animations from Building Up

    We have all done it. We build a super-awesome vertical menu with a little effect that makes text indentin an animated way on hover and slide back when the mouse leaves the link.

    The HTML

    Pg 3 of 24

  • 7/28/2019 Tutorial jQuery 001

    4/24

    Link #1

    Link #2

    Link #3

    Link #4

    Link #5

    Link #6

    Link #7

    Link #8

    Link #9

    Link #10

    The CSS

    body {

    font:0.8em Tahoma,Arial,sans-serif;

    padding:55px0075px;

    }

    #nav li {

    list-style:none;

    margin:0;

    display:block;

    }

    #nav li a {

    display:block;

    padding:6px6px6px12px;

    border-left:4px#dddsolid;

    background:#e5e5e5;font-size:110%;

    color:#666;

    text-decoration:none;

    }

    #nav li a:hover {

    color:#222;

    background:#d5d5d5;

    border-left-color:#ccc;

    }

    The jQuery

    Dont worry if you dont exactly understand everything that is going on; look underneath the code foran explanation of for each line.

    $("#nav > li a").hover( // this is called on when the mouse enters a link

    function(e){ // a variable contains HTML DOM object. Makes $this a jQuery object$this = $(this) // pointing to the same DOM element$this.animate({ // this animates the padding-left to 24px in 300 milliseconds

    // these are the CSS properties to animate to

    // there are no dashes. padding-left becomes paddingLeft

    paddingLeft :'24px'

    },300);

    },

    function(){ // this is called when the mouse leaves the link // variable contains HTML DOM object. Makes $this a jQuery object

    // pointing to the same DOM element

    $this = $(this) // animates, padding-left back to 12px (original value) in 300 milliseconds

    $this.animate({ // CSS properties to animate to

    // no dashes. padding-left becomes paddingLeft

    paddingLeft :'12px'

    },300);

    }

    );

    Explanation

    Lets translate this in to psuedo-English.

    Pg 4 of 24

  • 7/28/2019 Tutorial jQuery 001

    5/24

    When the users mouse hovers over a link we set the variable $this to be the jQuery object of theitem that the mouse is over. Then we use the jQuery function animate to increase the left paddingfrom 12px to 24px over a period of 300 milliseconds.

    When the use moves his/her mouse off the link, we once again set the variable $this to be the jQueryobject of the item that the mouse was over. We then animate the left padding back to 12px from 24pxover a period of 300 milliseconds.

    The Problem

    The problem is if someone hovers back-and-forth between two links really fast, the animations buildup and it slides back and forth without you doing anything. You can see what I am talking about onDemo #1.

    The Solution

    Fortunately, the solution is fairly simple. First, lets think about what we really need to do.

    1. We want to keep the animation from building up.2. If an animation is in progress we want to stop it immediately.

    3. We then need to move it in the other direction.

    This jQuery solves the issue (once again, look underneath the code for a highlight of the changes andan explanation of the code):

    $("#nav > li a").hover(

    function(e){ // this is called on when the mouse enters a link

    // this is a variable that contains a HTML DOM object. Makes $this a jQuery object

    $this = $(this) // pointing to the same DOM element

    $this.stop().animate({ // animates padding-left to 24px in 300 milliseconds

    paddingLeft :'24px' // CSS properties to animate

    },{queue:false,duration:300});

    },

    function(){ // this is called when the mouse leaves the link

    // variable contains HTML DOM object. Makes $this a jQuery object$this = $(this)// pointing to the same DOM element

    // animates, padding-left back to 12px (original value) in 300 milliseconds

    $this.animate({

    // these are the CSS properties to animate to

    // there are no dashes. padding-left becomes paddingLeft

    paddingLeft :'12px'

    },{queue:false,duration:300});

    }

    );

    Explanation

    Once again, all that jQuery might be too much for you all at once. Lets break it down again to psuedo-English.

    When the users mouse hovers over a link we set the variable $this to be the jQuery object of theitem that the mouse is over. Then we use the jQuery function animate to increase the left paddingfrom 12px to 24px over a period of 300 milliseconds and we tell jQuery to discard the animation queuefor this item and put this animation at the front. This helps prevents the dreaded animation buildup.Just changing the first part of the script isnt the only thing that has to be done. The biggest differencecomes in the next section.

    When the user moves his/her mouse off the link, we once again set the variable $this to be thejQuery object of the item that mouse was over. We then stop any animation on the current item

    Pg 5 of 24

    http://themeforest.s3.amazonaws.com/128_jquery/demo/demo_1.htmlhttp://themeforest.s3.amazonaws.com/128_jquery/demo/demo_1.htmlhttp://themeforest.s3.amazonaws.com/128_jquery/demo/demo_1.html
  • 7/28/2019 Tutorial jQuery 001

    6/24

    immediately. This is very important. We dont let the animation that makes the padding 24pxcomplete. If we did, we would once again have that problem with the animation buildup. We thenanimate the left padding back to 12px from 24px over a period of 300 milliseconds and once again weempty the animation queue and put this new animation at the front.

    Fixed Demo

    View the new demo. Let me highlight the specific changes:

    Changes in the Script

    1. Line 8: added .stop(): This stops all animation on that element, which helps prevent the buildup.

    2. Line 12: changed 300 to {queue:false,duration:300}: this makes it so queuing of animation isimpossible.

    3. Line 25: changed 300 to {queue:false,duration:300}: this makes it so queuing of animation isimpossible.

    Notice how on line 21, I didnt add .stop(), if I did, when the mouse would leave the link, it wouldntanimate and it would just stick part of the way out.

    6: What Does callback Mean

    For example: slideDown(speed, callback) function

    A callback is a function, or the name of a function that is run on the completion of the function youcalled. This is very, very useful on actions that take time to complete (for example: the SlideUpmethod). When I didnt know how to use a callback, I would use a timeout like this:

    $('#test').slideUp(400);

    setTimeout(function(){

    alert('ran after the slideup!');

    },400);

    Although this works fine, what if you dont know the length of the delay, like in an AJAX request?Sometimes the code would work, sometimes, not.

    The solution is to use the callback function. You have two options:

    1. You can create a function and then pass it as a string functionName2. You can use what is known as an anonymous function. This is a function that has no name is

    typically used only once.

    You can use the variable this in the callbacks. this is the HTML DOM object of the element, that in thiscase is being slid up. Like before, to manipulate it with jQuery you must use $(this). I usually preferthe anonymous method, but I will show you both:

    function makeAlert (){

    $(this).html('Ran this function!');

    }

    // both lines do the same thing

    $('#test').slideUp(400, makeAlert);

    $('#test').slideUp(400,function(){

    $(this).html('Ran the anonymous function!');

    });

    7: Doing Something when any AJAX Starts and Ends

    Pg 6 of 24

    http://themeforest.s3.amazonaws.com/128_jquery/demo/demo_2.htmlhttp://themeforest.s3.amazonaws.com/128_jquery/demo/demo_2.html
  • 7/28/2019 Tutorial jQuery 001

    7/24

    I used to manually show an animated GIF during an AJAX request to show that something washappening, and then manually hide it afterwards. jQuery provides us with some built-in methods thatallow us to run functions when any AJAX request starts and when any request completes. This makeslife much easier overall. For this example, I am going to assume that you already have some sort ofloading symbol (a div that says loading, an image, anything) with an id of loader. Here is the code:

    $('#loader').ajaxStart(function(){$(this).fadeIn();

    });

    $('#loader').ajaxStop(function(){

    $(this).fadeOut();});

    8: Doing Something Once the Images are Loaded

    Usually you dont need to wait until the images are loaded to run you jQuery, but if you aremanipulating images, then you need to wait until the images load, otherwise jQuery will (correctly)think that the width and height of the image is 0px by 0px. This is useful when you want to have

    jQuery automatically limit the size of image to fit the content. Fortunately this very easy:

    $(window).load(function(){// code to run once images load

    });

    Dont shift all of your $(document).ready() JavaScript into $(window).load() because then none of yourJavaScript will run until the images have been loaded, which is not what you want!

    The load method also works on any specific image. For example:

    $(document).ready(function(){$('#logo-image').load(function(){

    alert('finished loading the logo!');

    });

    });

    This time, I wrapped it in $(document).ready() because once the HTML is done loading, we know that

    there is supposed to be an image there and we can then make something happen once the imagefinally loads.

    9. Load the framework from Google Code

    Google have been hosting several JavaScript libraries for a while now on Google Code and there are several advantages to

    loading it from them instead of from your server. It saves on bandwidth, it'll load very quickly from Google's CDN and most

    importantly it'll already be cached if the user has visited a site which delivers it from Google Code.

    This makes a lot of sense. How many sites out there are serving up identical copies of jQuery that aren't getting cached? It's

    easy to do too...

    view plain copy to clipboard print ?

    // Load jQuery

    google.load("jquery", "1.2.6");

    google.setOnLoadCallback(function() {

    Pg 7 of 24

    http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23
  • 7/28/2019 Tutorial jQuery 001

    8/24

  • 7/28/2019 Tutorial jQuery 001

    9/24

    for (i = 0; i < 1000; i++) {

    var myList = $('.myList');

    myList.append('This is list item ' + i);

    }

    console.timeEnd('create list');

    In this instance I've deliberately written some very inefficient code! In the next few tips I'll show you how we can use the timer

    to show some improvements which can be made.

    13. Keep selection operations to a minimum by caching

    jQuery selectors are awesome. They make selecting any element on the page incredibly simple, but internally they have to

    do a fair amount of work and if you go mad with them you might find things starting to get pretty slow.

    If you're selecting the same element time and time again (in a loop for example) then you can just select it once and keep it

    in memory while you manipulate it to your heart's content. Take the following example where we add items to an unordered

    list using a loop.

    view plain copy to clipboard print ?

    for (i = 0; i < 1000; i++) {

    var myList = $('.myList');

    myList.append('This is list item ' + i);

    }

    That takes 1066 milliseconds on my PC in Firefox 3 (imagine how long it would IE6!), which is pretty slow in JavaScript

    terms. Now take a look at the following code where we use the selector just once.

    view plain copy to clipboard print ?

    var myList = $('.myList');

    for (i = 0; i < 1000; i++) {

    myList.append('This is list item ' + i);

    }

    That only takes 224 milliseconds, more than 4x faster, just by moving one line of code.

    14. Keep DOM manipulation to a minimum

    We can make the code from the previous tip even faster by cutting down on the number of times we insert into the DOM.

    DOM insertion operations like .append() .prepend() .after() and .wrap() are relatively costly and performing lots of them can

    really slow things down.

    Pg 9 of 24

    http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23
  • 7/28/2019 Tutorial jQuery 001

    10/24

    All we need to do is use string concatenation to build the list and then use a single function to add them to your unordered

    list like .html() is much quicker. Take the following example...

    view plain copy to clipboard print ?

    var myList = $('#myList');

    for (i=0; i

  • 7/28/2019 Tutorial jQuery 001

    11/24

    jQuery makes selecting DOM elements using classes as easy as selecting elements by ID used to be, so it's tempting to use

    classes much more liberally than before. It's still much better to select by ID though because jQuery uses the browser's

    native method (getElementByID) to do this and doesn't have to do any of it's own DOM traversal, which is much faster. How

    much faster? Let's find out.

    I'll use the previous example and adapt it so each LI we create has a unique class added to it. Then I'll loop through and

    select each one once.

    view plain copy to clipboard print ?

    // Create our list

    var myList = $('.myList');

    var myListItems = '';

    for (i = 0; i < 1000; i++) {

    myListItems += 'This is a list item';

    }

    myListItems += '';

    myList.html(myListItems);

    // Select each item once

    for (i = 0; i < 1000; i++) {

    var selectedItem = $('.listItem' + i);

    }

    Just as I thought my browser had hung, it finished, in 5066 milliseconds (over 5 seconds). So i modified the code to give

    each item an ID instead of a class and then selected them using the ID.

    view plain copy to clipboard print ?

    // Create our list

    var myList = $('.myList');

    var myListItems = '';

    for (i = 0; i < 1000; i++) {

    myListItems += 'This is a list item';

    }

    myListItems += '';

    myList.html(myListItems);

    // Select each item once

    for (i = 0; i < 1000; i++) {

    var selectedItem = $('#listItem' + i);

    }

    This time it only took 61 milliseconds. Nearly 100x faster.

    17. Give your selectors a context

    By default, when you use a selector such as $('.myDiv') the whole of the DOM will be traversed, which depending on the

    Pg 11 of 24

    http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23
  • 7/28/2019 Tutorial jQuery 001

    12/24

    page could be expensive.

    The jQuery function takes a second parameter when performing a selection.

    jQuery( expression, context )

    By providing a context to the selector, you give it an element to start searching within so that it doesn't have to traverse thewhole of the DOM.

    To demonstrate this, let's take the first block of code from the tip above. It creates an unordered list with 1000 items, each

    with an individual class. It then loops through and selects each item once. You'll remember that when selecting by class it

    took just over 5 seconds to select all 1000 of them using this selector.

    view plain copy to clipboard print ?

    var selectedItem = $('#listItem' + i);

    I then added a context so that it was only running the selector inside the unordered list, like this...

    view plain copy to clipboard print ?

    var selectedItem = $('#listItem' + i, $('.myList'));

    It still took 3818 milliseconds because it's still horribly inefficient, but that's more than a 25% speed increase by making a

    small modification to a selector.

    18. Use chaining properly

    One of the coolest things about jQuery is it's ability to chain method calls together. So, for example, if you want to switch the

    class on an element.

    view plain copy to clipboard print ?

    $('myDiv').removeClass('off').addClass('on');

    If you're anything like me then you probably learned that in your first 5 minutes of reading about jQuery but it goes further

    than that. Firstly, it still works across line breaks (because jQuery = JavaScript), which means you can write neat code like

    this...

    view plain copy to clipboard print ? $('#mypanel')

    .find('TABLE .firstCol')

    .removeClass('.firstCol')

    .css('background' : 'red')

    .append('This cell is now red');

    Making a habit of using chaining automatically helps you to cut down on your selector use too.

    Pg 12 of 24

    http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23
  • 7/28/2019 Tutorial jQuery 001

    13/24

    But it goes further than that. Let's say that you want to perform several functions on an element but one of the first functions

    changes the element in some way, like this...

    view plain copy to clipboard print ?

    $('#myTable').find('.firstColumn').css('background','red');

    We've selected a table, drilled down to find cells with a class of "firstColumn" and coloured them in red.

    Let's say we now want to colour all the cells with a class of "lastColumn" blue. Because we've used the find() funciton we've

    filtered out all the cells that don't have a class of "firstColumn" so we need to use the selector again to get the table element

    and we can't continue chaining, right? Luckily jQuery has an end() function which actually reverts back to the previous

    unaltered selection so you can carry on chaining, like this...

    view plain copy to clipboard print ?

    $('#myTable')

    .find('.firstColumn')

    .css('background','red')

    .end()

    .find('.lastColumn')

    .css('background','blue');

    It's also easier than you might think to write your own jQuery function which can chain. All you have to do is write a function

    which modifies an element and returns it.

    view plain copy to clipboard print ?

    $.fn.makeRed = function() {

    return $(this).css('background', 'red');

    }

    $('#myTable').find('.firstColumn').makeRed().append('hello');

    How easy was that?

    19. Learn to use animate properly

    When I first started using jQuery I loved the fact that it was easy to use the pre-defined animations like slideDown() and

    fadeIn() to get some really cool effects incredibly easy. It's easy to take things further though because jQuery's animate()

    method is very easy to use and very powerful. In fact, is you look at the jQuery source code you'll see that internally those

    methods are just shortcuts which use the animate() function.

    view plain copy to clipboard print ?

    slideDown: function(speed,callback){

    returnthis.animate({height: "show"}, speed, callback);

    },

    fadeIn: function(speed, callback){

    returnthis.animate({opacity: "show"}, speed, callback);

    }

    Pg 13 of 24

    http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23
  • 7/28/2019 Tutorial jQuery 001

    14/24

    The animate() method simply takes any CSS style and smoothly transitions it from one value to another. So, you can change

    the width, height, opacity, background-color, top, left, margin, color, font-size, anything you want.

    This is how easy it is to animate all your menu items grow to 100 pixels high when you roll over them.

    view plain copy to clipboard print ?

    $('#myList li').mouseover(function() {

    $(this).animate({"height": 100}, "slow");

    });

    Unlike other jQuery functions, animations are automatically queued, so if you want to run a second animation once the first is

    finished then just call the animate method twice, no callback necessary.

    view plain copy to clipboard print ?

    $('#myBox').mouseover(function() {

    $(this).animate({ "width": 200 }, "slow");

    $(this).animate({"height": 200}, "slow");

    });

    If you want the animations to happen concurrently then just put both styles in the params object of a single call, like this...

    view plain copy to clipboard print ?

    $('#myBox').mouseover(function() {

    $(this).animate({ "width": 200, "height": 200 }, "slow");

    });

    You can animate any property that's numeric. You can also download plugins to help you animate properties that aren't, like

    colors and background colors

    20. Learn about event delegation

    jQuery makes it easier than ever to attach events to elements in the DOM unobtrusively, which is great, but adding too many

    events is inefficient. Event delegation allows you to add less events to achieve the same result in many situations. The best

    way to illustrate this is with an example...

    view plain copy to clipboard print ?

    $('#myTable TD').click(function(){

    $(this).css('background', 'red');

    });

    A simple function which turns cells in a table red when you click on them. Let's say that you've got a grid with 10 columns

    and 50 rows though, that's 500 events bound. Wouldn't it be neater if we could just attach a single event to the table and

    when the table is clicked have the event handler work out which cell was clicked before turning it red?

    Well that's exactly what event delegation is and it's easy to implement...

    Pg 14 of 24

    http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://plugins.jquery.com/project/colorhttp://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://plugins.jquery.com/project/colorhttp://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23
  • 7/28/2019 Tutorial jQuery 001

    15/24

    view plain copy to clipboard print ?

    $('#myTable').click(function(e) {

    var clicked = $(e.target);

    clicked.css('background', 'red');

    });

    'e' contains information about the event, including the target element that actually received the click. All we have to do is

    inspect it to see which cell was actually clicked. Much neater.

    Event delegation has another benefit. Normally, When you bind a handler to a collection of elements it gets attached to

    those elements and those elements only. If you add new elements to the DOM which would have been matched by the

    selector then they don't have the event handler bound to them (are you following me?) then nothing will happen.

    When using event delegation you can add as many matching elements to the DOM as you like after the event is bound and

    they work too.

    21. Use classes to store state

    This is the most basic way of storing information about a block of html. jQuery is great at manipulating elements based upon

    their classes, so if you need to store information about the state of an element then why not add an extra class to store it?

    Here's an example. We want to create an expanding menu. When you click the button we want the panel to slideDown() if

    it's currently closed, or slideUp() if it's currently open. We'll start with the HTML

    view plain copy to clipboard print ?

    click me

    Menu item 1

    Menu item 2

    Menu item 3

    Very simple! We've just added an extra class to the wrapper div which serves no other purpose other than to tell us the state

    of the item. So all we need is a click event handler which performs slideUp() or slideDown() on the corresponding panel

    when the button is clicked.

    view plain copy to clipboard print ?

    $('.button').click(function() {

    var menuItem = $(this).parent();

    var panel = menuItem.find('.panel');

    Pg 15 of 24

    http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23
  • 7/28/2019 Tutorial jQuery 001

    16/24

    if (menuItem.hasClass("expanded")) {

    menuItem.removeClass('expanded').addClass('collapsed');

    panel.slideUp();

    }

    elseif (menuItem.hasClass("collapsed")) {

    menuItem.removeClass('collapsed').addClass('expanded');

    panel.slideDown();

    }

    });

    That's a very simple example, but you can add extra classes for storing all sorts of information about an element or HTML

    fragment.

    However, in all but simple cases it's probably better to use the next tip.

    22. Even better, use jQuery's internal data() method to store state

    It's not very well documented for some reason but jQuery has an internal data() method which can be used to store

    information in key/value pairs against any DOM element. Storing a piece of data is as simple as this...

    view plain copy to clipboard print ?

    $('#myDiv').data('currentState', 'off');

    We can amend the example from the previous tip. We'll use the same HTML (with the "expanded" class removed) and use

    the data() function instead.

    view plain copy to clipboard print ?

    $('.button').click(function() {

    var menuItem = $(this).parent();

    var panel = menuItem.find('.panel');

    if (menuItem.data('collapsed')) {

    menuItem.data('collapsed', false);

    panel.slideDown();

    }

    else {

    menuItem.data('collapsed', true);

    panel.slideUp();

    }

    });

    I'm sure you'll agree this is much neater. For more information about data() and removeData(), see this page...

    jQuery internals

    23. Write your own selectors

    jQuery has loads of built-in selectors for selecting elements by ID, class, tag, attribute and many more. But what do you do

    Pg 16 of 24

    http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://docs.jquery.com/Internalshttp://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://docs.jquery.com/Internals
  • 7/28/2019 Tutorial jQuery 001

    17/24

    when you need to select elements based upon something else and jQuery doesn't have a selector?

    Well, one answer would be to add classes to the elements from the start and use those to select them, but it turns out that

    it's not hard to extend jQuery to add new selectors.

    The best way to demonstrate is with an example.

    view plain copy to clipboard print ?

    $.extend($.expr[':'], {

    over100pixels: function(a) {

    return $(a).height() > 100;

    }

    });

    $('.box:over100pixels').click(function() {

    alert('The element you clicked is over 100 pixels high');

    });

    The first block of code creates a custom selector which finds any element that is more than 100 pixels tall. The second block

    just uses it to add a click handler to all those elements.

    I won't go into any more detail here but you can imagine how powerful this is and if you search google for "custom jquery

    selector" you'll find loads of great examples.

    24. Streamline your HTML and modify it once the page has loaded

    The title might not make a lot of sense but this tip can potentially neaten up your code, reduce the weight and download time

    of your page and help your SEO. Take the following HTML for example...

    view plain copy to clipboard print ?

    This is field number 1

    This is an error message

    This is field number 2

    This is an error message

    Pg 17 of 24

    http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23
  • 7/28/2019 Tutorial jQuery 001

    18/24

    That's an example of how a form might be marked up, modified slightly for illustrative purposes. I'm sure you'll agree it's

    pretty ugly and if you had a long form you'd end up with a fairly long ugly page. It's be nicer if you could just put this in your

    HTML.

    view plain copy to clipboard print ?

    This is field 1

    This is field 2 This is field 3

    This is field 4

    This is field 5

    All you have to do is a bit of jQuery manipulation to add all the ugly HTML back in. Like this...

    view plain copy to clipboard print ?

    $(document).ready(function() {

    $('.field').before('');

    $('.field').after('

    This is an error message');

    });

    It's not always advisable to do this, you'll get a bit of a flash as the page loads, but in certain situations where you've got a lot

    of repeated HTML it can really reduce your page weight and the SEO benefits of reducing all your repeated extraneous

    markup should be obvious.

    25. Lazy load content for speed and SEO benefits

    Another way to speed up your page loads and neaten up the HTML that search spiders see is to lazy load whole chunks of it

    using an AJAX request after the rest of the page has loaded. The user can get browsing right away and spiders only see the

    content you want them to index.

    We've used this technique on our own site. Those purple buttons at the top of the page drop down 3 forms, directions and a

    google map, which was doubling the size of our pages. So, we just put all that HTML in a static page and use the load()

    function to load it in once the DOM was ready. Like this...

    view plain copy to clipboard print ?

    $('#forms').load('content/headerForms.html', function() {

    // Code here runs once the content has loaded

    // Put all your event handlers etc. here.

    });

    I wouldn't use this everywhere. You have to consider the trade offs here. You're making extra requests to the server and

    portions of your page might not be available to the user right away, but used correctly it can be a great optimization

    technique.

    Pg 18 of 24

    http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23
  • 7/28/2019 Tutorial jQuery 001

    19/24

    26. Use jQuery's utility functions

    jQuery isn't just about flash effects. The creator has exposed some really useful methods which fill a few gaps in JavaScript's

    repertoire.

    http://docs.jquery.com/Utilities

    In particular, browser support for certain common array functions is patchy (IE7 doesn't even have an indexOf() method!).Jquery has methods for iterating, filtering, cloning, merging and removing duplicates from Arrays.

    Other common functions that are difficult in Javascript include getting the selected item in a drop down list. In plain old

    JavaScript you'd have to get the element using getElementByID, get the child elements as an array and iterate

    through them checking whether each one was selected or not. jQuery makes it easy...

    view plain copy to clipboard print ?

    $('#selectList').val();

    It's worth spending some time looking through the jQuery documentation on the main site and having a nose around some of

    the lesser known functions.

    27. Use noconflict to rename the jquery object when using other frameworks

    Most javascript frameworks make use of the $ symbol as a shorthand and this can cause clashes when trying to use more

    than one framework on the same page. Luckily there's a simple solution. The .noconflict() function gives control of the $ back

    and allows you to set your own variable name, like this...

    view plain copy to clipboard print ?

    var $j = jQuery.noConflict();

    $j('#myDiv').hide();

    28. How to tell when images have loaded

    This is another one of those problems that doesn't seem to be as well documented as it should be (not when I went looking

    anyway) and it's a fairly common requirement when building photo galleries, carousels etc, but it's fairly easy.

    All you have to do is use the .load() method on an IMG element and put a callback function in it. The following example

    changes the "src" attribute of an image tag to load a new image and attaches a simple load function.

    view plain copy to clipboard print ?

    $('#myImage').attr('src', 'image.jpg').load(function() {

    alert('Image Loaded');

    });

    You should find that the alert is called as soon as the image is loaded.

    Pg 19 of 24

    http://docs.jquery.com/Utilitieshttp://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://docs.jquery.com/Utilitieshttp://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23
  • 7/28/2019 Tutorial jQuery 001

    20/24

    29. Always use the latest version

    jQuery is constantly improving and John Resig, it's creator, always seems to be in search of ways to improve performance.

    jQuery is currently on version 1.2.6 but John has already revealed that he's working on a new selector engine called Sizzle,

    which may apparently improve selector speeds in Firefox by up to 4x. So, it pays to keep up to date.

    30. How to check if an element exists

    You don't need to check if an element exists on the page before you manipulate it because jQuery will will simply do nothing

    if you try to select something and it isn't in the DOM. But when you do need to check if anything has been selected, or how

    many items have been selected you can use the length property.

    view plain copy to clipboard print ?

    if ($('#myDiv).length) {

    // your code

    }

    Simple, but not obvious.

    31. Add a JS class to your HTML attribute

    I learned this tip from Karl Swedberg whoseexcellentbooks I used to learn jQuery.

    He recently left a comment on one of my previous articles about this technique and the basics are as follows...

    Firstly, as soon as jQuery has loaded you use it to add a "JS" class to your HTML tag.

    view plain copy to clipboard print ?

    $('HTML').addClass('JS');

    Because that only happens when javascript is enabled you can use it to add CSS styles which only work if the user has

    JavaScript switched on, like this...

    view plain copy to clipboard print ?

    .JS #myDiv{display:none;}

    So, what this means is that we can hide content when JavaScript is switched on and then use jQuery to show it when

    necessary (e.g. by collapsing some panels and expanding them when the user clicks on them), while those with JavaScript

    off (and search engine spiders) see all of the content as it's not hidden. I'll be using this one a lot in the future.

    To read his full article click here.

    32. Return 'false' to prevent default behavior

    This should be an obvious one but maybe not. if you have a habit of doing this...

    view plain copy to clipboard print ?

    Pg 20 of 24

    http://ajaxian.com/archives/sizzle-john-resig-has-a-new-selector-enginehttp://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.amazon.co.uk/Learning-JQuery-Interaction-Development-Javascript/dp/1847192505/ref=sr_1_1?ie=UTF8&s=books&qid=1229284831&sr=8-1http://www.amazon.co.uk/Learning-JQuery-Interaction-Development-Javascript/dp/1847192505/ref=sr_1_1?ie=UTF8&s=books&qid=1229284831&sr=8-1http://www.amazon.co.uk/JQuery-Reference-Guide-Karl-Swedberg/dp/1847193811/ref=sr_1_3?ie=UTF8&s=books&qid=1229284831&sr=8-3http://www.amazon.co.uk/JQuery-Reference-Guide-Karl-Swedberg/dp/1847193811/ref=sr_1_3?ie=UTF8&s=books&qid=1229284831&sr=8-3http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.learningjquery.com/2008/10/1-awesome-way-to-avoid-the-not-so-excellent-flash-of-amazing-unstyled-contenthttp://www.learningjquery.com/2008/10/1-awesome-way-to-avoid-the-not-so-excellent-flash-of-amazing-unstyled-contenthttp://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://ajaxian.com/archives/sizzle-john-resig-has-a-new-selector-enginehttp://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.amazon.co.uk/Learning-JQuery-Interaction-Development-Javascript/dp/1847192505/ref=sr_1_1?ie=UTF8&s=books&qid=1229284831&sr=8-1http://www.amazon.co.uk/JQuery-Reference-Guide-Karl-Swedberg/dp/1847193811/ref=sr_1_3?ie=UTF8&s=books&qid=1229284831&sr=8-3http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.learningjquery.com/2008/10/1-awesome-way-to-avoid-the-not-so-excellent-flash-of-amazing-unstyled-contenthttp://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23
  • 7/28/2019 Tutorial jQuery 001

    21/24

    Click me!

    ... and then attaching an event handler like this...

    view plain copy to clipboard print ?

    $('popup').click(function(){

    // Launch popup code

    });

    ... it'll probably work fine until you use it on a long page, at which point you'll notice that the # is causing it to jump to the top

    of the page when your click event is triggered.

    All you have to do to prevent this default behaviour, or indeed any default behaviour on any event handler is to add "return

    false;" to your handler, like this...

    view plain copy to clipboard print ?

    $('popup').click(function(){

    // Launch popup code

    returnfalse;

    });

    33. Shorthand for the ready event

    A small tip this one but you can save a few characters by using shorthand for the $(document).ready function.

    Instead of this...

    view plain copy to clipboard print ?

    $(document).ready(function (){

    // your code

    });

    You can do this...

    view plain copy to clipboard print ?

    $(function (){

    // your code

    });

    34. Moving Off Links

    Pg 21 of 24

    http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#%23
  • 7/28/2019 Tutorial jQuery 001

    22/24

    How does Jquery handle moving off links? In Javascript it is onmouseout . In jQuery, it is the the

    second argument in click. Example:

    $('#something').click(function () {

    // onmouseover

    }, /* second argument!! */ function () {

    // onmouseout

    });

    Pg 22 of 24

  • 7/28/2019 Tutorial jQuery 001

    23/24

    Appendix A

    Demo #1 Listing

    Demo #1 7 Things I Wish I Had Known About jQuery

    body {

    font:0.8em Tahoma,Arial,sans-serif;

    padding:55px 0 0 75px;

    }

    #nav li {list-style:none;

    margin:0;

    display:block;

    }

    #nav li a {

    display:block;

    padding:6px 6px 6px 12px;

    border-left:4px #ddd solid;

    background:#e5e5e5;

    font-size:110%;

    color:#666;

    text-decoration:none;

    }#nav li a:hover {

    color:#222;

    background:#d5d5d5;

    border-left-color:#ccc;

    }

    $(function () {

    $("#nav > li a").hover(

    // this is called on when the mouse enters a link

    function (e) {

    // this is a variable that contains a HTML

    DOM object. This makes $this a jQuery object

    // pointing to the same DOM element

    $this = $(this)

    // this animates the padding-left to 24px in

    300 milliseconds

    $this.animate({

    // these are the CSS properties to

    animate to

    // there are no dashes. padding-left

    becomes paddingLeft

    Pg 23 of 24

  • 7/28/2019 Tutorial jQuery 001

    24/24

    paddingLeft : '24px'

    }, 300);

    },

    // this is called when the mouse leaves the link

    function () {

    // this is a variable that contains a HTML

    DOM object. This makes $this a jQuery object

    // pointing to the same DOM element

    $this = $(this)

    // this animates the padding-left back to12px (the original value) in 300 milliseconds

    $this.animate({

    // these are the CSS properties to

    animate to

    // there are no dashes. padding-left

    becomes paddingLeft

    paddingLeft : '12px'

    }, 300);

    }

    );

    });

    Link #1

    Link #2

    Link #3

    Link #4

    Link #5

    Link #6

    Link #7

    Link #8

    Link #9

    Link #10