Download PDF : jQuery tips tips

Download document : jQuery tip tip






Download PDF : jQuery tips tips























Table of Contents

1.   Objects and Methods
2.   Jquery is Chainable
3:   jQuery can Behave Somewhat like an Array
4:   jQuery in a Variable
5:   Keep Animations from Building Up
6:   What Does ‘callback’ Mean
7:   Do Something when any AJAX Starts/Ends
8.   Load the framework from Google Code
9.   Use a cheat sheet
10. Combine all your scripts and minify them
11. Use Firebug's console logging facilities
12. Keep selection to a minimum by caching
13. Keep DOM manipulation to a minimum
14. Wrap to single element doing DOM insertion
15. Use IDs instead of classes wherever possible
16. Give selectors a context
17. Use chaining properly
18. Animate properly
19. Event delegation
20. Use classes to store state
21. Use jQuery's data() method to store state
22. Write your own selectors
23. Streamline HTML, modify after page load
24. Load content for speed and SEO benefits
25. Use jQuery's utility functions
26. Use noconflict to rename jquery object
27. How to tell when images have loaded
28. Always use the latest version
29. How to check if an element exists
30. Add a JS class to your HTML attribute
31. Return 'false' to prevent default behaviour
32. Shorthand for the ready event


***************



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 of it may be to shine (an action). And when it’s shining, its brightness property would be of a greater value than when it wasn’t.

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

Use the following code as an example:
var testText = $('div#test').text();
This sets the value of the variable testText with the text of the div with the id of test; pretty straightforward.
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 the jQuery documentation. ‘text’ is a method that returns ‘[the] combined text contents of all matched elements.’ (from here).

2. Jquery is Chainable
JavaScript is ‘chainable’. ‘Chainable’ means you can have multiple methods joined together. For example this jQuery:
var testText = $('div#test').parent().text();
…and this HTML:

<div id="test">This is the content!</div>
That code would return the text of the parent of the div with the id of ‘test’. The parent method returned a new jQuery object containing the element’s parent.
Not all things are chainable. For example the text method doesn’t return a jQuery object, it returns a string. You use the parent method on a string, because that doesn’t make any sense at all. However, because it returns a string you can use all the methods that you can use with a string. These methods are documented very well here. For example, it is perfectly fine to use the split method 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 items in 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 many items are in an array using ‘arrayVariable.length’. You can do the same with jQuery. Each object that matches the specified selectors is an item in the array. Look at this:
/*
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 4
var num = $('#wrapper .box');
num = num.length;

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

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

// text is equal to 'Content2 #1'
var text = $("#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'
var testHTML = $testBox.html();

5: Keep Animations from Building 

We have all done it. We build a super-awesome vertical menu with a little effect that makes text indent in an animated way on hover and slide back when the mouse leaves the link.
The HTML
<ul id="nav">
         <li><a href="#">Link #1</a></li>
         <li><a href="#">Link #2</a></li>
         <li><a href="#">Link #3</a></li>
         <li><a href="#">Link #4</a></li>
         <li><a href="#">Link #5</a></li>
         <li><a href="#">Link #6</a></li>
         <li><a href="#">Link #7</a></li>
         <li><a href="#">Link #8</a></li>
         <li><a href="#">Link #9</a></li>
         <li><a href="#">Link #10</a></li>
</ul>
The CSS
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;
}
The jQuery
Don’t worry if you don’t exactly understand everything that is going on; look underneath the code for an 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
Let’s translate this in to psuedo-English.

When the user’s mouse hovers over a link we set the variable ‘$this’ to be the jQuery object of the item that the mouse is over. Then we use the jQuery function ‘animate’ to increase the left padding from 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 jQuery object of the item that the mouse was over. We then animate the left padding back to 12px from 24px over a period of 300 milliseconds.

The Problem
The problem is if someone hovers back-and-forth between two links really fast, the animations build up and it slides back and forth without you doing anything. You can see what I am talking about on Demo #1.
The Solution
Fortunately, the solution is fairly simple. First, let’s 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 and an 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. Let’s break it down again to psuedo-English.
When the user’s mouse hovers over a link we set the variable ‘$this’ to be the jQuery object of the item that the mouse is over. Then we use the jQuery function ‘animate’ to increase the left padding from 12px to 24px over a period of 300 milliseconds and we tell jQuery to discard the animation queue for this item and put this animation at the front. This helps prevents the dreaded “animation buildup”. Just changing the first part of the script isn’t the only thing that has to be done. The biggest difference comes in the next section.
When the user moves his/her mouse off the link, we once again set the variable ‘$this’ to be the jQuery object of the item that mouse was over. We then stop any animation on the current item immediately. This is very important. We don’t let the animation that makes the padding 24px complete. If we did, we would once again have that problem with the “animation buildup”. We then animate the left padding back to 12px from 24px over a period of 300 milliseconds and once again we empty 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 build up.
  2. Line 12: changed 300 to {queue:false,duration:300}: this makes it so queuing of animation is impossible.
  3. Line 25: changed 300 to {queue:false,duration:300}: this makes it so queuing of animation is impossible.
Notice how on line 21, I didn’t add .stop(), if I did, when the mouse would leave the link, it wouldn’t animate 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 you called. This is very, very useful on actions that take time to complete (for example: the SlideUp method). When I didn’t 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 don’t 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 ‘functionName’
  2. 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 this case is being slid up. Like before, to manipulate it with jQuery you must use ‘$(“this”)’. I usually prefer the 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
I used to manually show an animated GIF during an AJAX request to show that something was happening, and then manually hide it afterward........







0 commentaires: