7 Things I Wish I Had Known About jQuery

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

  • 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 don’t know anything about how to use jQuery you should read this. This is not meant to be an introduction to jQuery. This is meant for people who have tried jQuery and may have been frustrated because they weren’t sure how to do something correctly.

1: Some Background Info

Objects and Methods

I know when I started learning jQuery, I wasn’t too familiar with objects and methods.

Think of it this way:

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 Tim Scarfe

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).

Chainability

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.

2: 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:
<div id="wrapper">
	<div class="box">Content #1!</div>
	<div class="box">Content #2!</div>
	<div class="box">Content #3!</div>
	<div class="box">Content #4!</div>
</div>
<div id="wrapper2">
	<div class="box">Content2 #1!</div>
</div>
*/
 
// 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];

3: 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();

4: Keep Animations from Building Up

Vertical Menu With Hover Effect

We have all done it. We build a super-awesome vertical menu with a little effect that makes text indent in a 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) {
		// 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
			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 to 12px (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);
	}
);

Explanation

Throwing all that jQuery at you all at once might be a bit confusing. Let’s translate it 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(
	// 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.stop().animate({
			// these are the CSS properties to animate to
			// there are no dashes. padding-left becomes paddingLeft
			paddingLeft : '24px'
		}, {queue:false,duration: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 to 12px (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'
		}, {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.

5: What Does ‘callback’ Mean

WTF is a callback?

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!');
});

6: 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 afterwards. jQuery provides us with some built-in methods that allow us to run functions when any AJAX request starts and when any request completes. This makes life much easier overall. For this example, I am going to assume that you already have some sort of loading 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();
});

7: Doing Something Once the Images are Loaded

Usually you don’t need to wait until the images are loaded to run you jQuery, but if you are manipulating 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
});

Don’t shift all of your $(document).ready() JavaScript into $(window).load() because then none of your JavaScript 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 image finally loads.

Which Tips Helped you the Most When First Learning?


31

Comments

Discuss This Post on the ThemeForest Forums