Nov 14, 2012
Table of contents:
jQuery is a Javascript Library that makes working with Javascript on web pages a lot easier. If you’ve created websites in the past, you will know that making a website that looks exactly the same across multiple browsers can be tricky. Writing Javascript is no different, and so something that functions perfectly in one browser, might not work at all in another.
The beautiful thing about jQuery is, it is essentially an abstraction layer between you and the browser. If you read the Roll your own PDO PHP Class tutorial, you will remember that an abstraction layer is just something that sits in the middle to make things easier. In this case, jQuery allows you to write your Javascript once, and it will work across all browsers.
This might seem complicated, but jQuery is just a regular Javascript file that you load into your webpage like you would with any other Javascript file. You will still need to know Javascript, but actually creating real working stuff will be easier with jQuery.
Before reading this tutorial, you might also want to take a look at my previous Javascript posts
jQuery makes it easy to write code to:
Don’t worry if this seems a lot to take in at once, I’ll be covering each section in manageable chunks.
So there must be some negative things with using jQuery, right?
Well, jQuery is another resource you need to load when a user visits your website. This might not be a problem for desktop computers on broadband, but it could become an issue if you have a particularly resource heavy website that is accessed on a phone over mobile Internet.
Secondly, as I alluded to in my first PHP PDO tutorial (Prevent PHP SQL Injection with PDO Prepared Statements), using an abstraction layer is great for getting up and going quickly, or solving a problem that someone else has already solved, but you won’t fully understand what is going on under the hood. Although you don’t need to know a lot of Javascript to use jQuery, you won’t become a better Developer without taking the time to fully understand what is happening in the background.
There are a couple of different options for getting and using jQuery that you should be aware of.
If you go to jQuery.com you will see an option to download it. jQuery comes in two different flavours, Regular and Minified.
The Regular version of jQuery weighs in at a hefty 252kb, whereas the Minified version is a much smaller 32kb.
Both files have exactly the same functionality, the smaller size is due to the way the code is written.
When you Minify a file, you use as few characters and spaces as possible to reduce the file size. So a function might make the following change.
// Regular
function addTheCostofTwoItems (item1, item2) {
return item1 + item 2;
}
// Minified
function a(i,j) {return i+j;}
As you can see, the Minified version works exactly the same, but it is a lot harder to understand what’s going on and what the function is for. So during Development, when you want to troubleshoot your code, it’s best to use the Regular version, but for live websites, always use the Minified version.
The second thing to consider is where to load jQuery from. If you download jQuery you can use it just like any other Javascript file by keeping it within the same file system as the rest of your website project and by uploading it to your server.
However, there is another way.
Google hosts jQuery on their Content Distribution Network. This means you don’t have to upload and serve the file from your server. jQuery is also extremely popular. If your user has been on a website that also used the same version of jQuery that you are using, they will already have the file cached on their computer. This means when they arrive at your website, jQuery won’t have to be downloaded again.
To follow along with this tutorial, create a new HTML file with the following code:
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</html>
Save that file and open it in a browser. For this tutorial I will be using Google Chrome and I will be using the Javascript Console which you can find under the Tools menu.
Once you have your HTML file loaded, open the Console and type:
jQuery;
You should get back something like:
function (a,b) {return new p.fn.init(a,b,c)}
This is a good sign, it means jQuery has loaded correctly.
Instead of typing jQuery, you could also just use the dollar sign:
$;
// Also returns function (a,b) {return new p.fn.init(a,b,c)}
The $ sign can be used interchangeably with jQuery. It is essentially just a reference to the jQuery library. So when looking at jQuery code, you will often see the $ sign. This has no special meaning, it just references jQuery.
An important concept of jQuery (and Javascript) is The DOM (Document Object Model). The DOM is the structure of a web page.
When you load a web page, the browser downloads the HTML and organises it in the structure of the DOM. Essentially, the DOM just organises the code into a structure like a tree. This enables Javascript to read and manipulate the elements within the tree. If you are familiar with XML, the DOM is similar to the node structure you find in XML.
For this tutorial we are going to need some HTML to work with. Copy and paste the following into the file we created earlier, inbetween the body tags.
<div id="navigation">
<ul>
<li>first</li>
<li>second</li>
<li>third</li>
</ul>
</div>
<div>
<p id="introduction">
Introduction...
<span class="more">Read more</span>
</p>
<p>Some more information</p>
<p id="conclusion">
Conclusion
<span class="more">Find out more!</span>
</p>
</div>
<span id="footer">Footer information</span>
Save your file and refresh your browser.
The first thing you are going to need to learn to do is how to select elements on the page, as this is fundamental to how jQuery works.
The structure of a jQuery selector is like this:
$("div");
So we have the $ sign, open parenthesis, speech marks, the tag we want to find, close speech marks, close parenthesis and a semicolon.
Here we are simply telling jQuery to select all of the div tags from the DOM.
So if you write that into the Javascript Console in your browser you should be returned all the divs and content of your HTML code in an array. If you remember back to the previous Javascript tutorials, an array is denoted by square braces [ ].
Try typing the following into your Console:
$("table");
You should be returned a [], blank array. So whenever you search for an element, you will always be returned an array, even if that element was not found. Javascript considers an empty array to be a true value. So any true / false comparison will return true, even though the array is empty. This is an important thing to remember when writing jQuery.
In order to pick out elements more precisely, we can use the Id and Class names that appear in the HTML. For example:
$("p#introduction");
$("span.more");
If you want to select multiple elements, you just pass jQuery a comma separated list:
$("div#introduction, p#introduction");
Now that you understand how jQuery selectors work, lets look at some more advanced and practical examples.
Say you wanted to select the unordered list from within the div. We could write:
$("div ul");
This will only look for ul tags that sit within a div.
We could be even more precise by using the id too.
$("div#navigation ul");
If you wanted to pick the first or last element, you can use a Pseudo class.
$("ul li:last");
This would only select the last list element within the unordered list.
Next, if we wanted to only pick spans that were a direct descendent of an element, we could do it like this:
$("p#introduction > span");
This would only select the span in the introduction because it is a direct descendent of the introduction paragraph.
Now that you know how to make selections, we can start manipulating it.
jQuery is really useful if you want to change the CSS properties of something. For example, you might want to change the colour of something after a certain action.
To edit the CSS of an element, we can use the CSS function.
To use the CSS function, first select which element you want to manipulate:
$("div#navigation");
Next, add the CSS function and the property you want to change.
$("div#navigation").css("background-color");
If you run the jQuery in the console, you should be returned the current CSS value of the CSS property on the element you selected. To change the property, just add a second string into the CSS function:
$("div#navigation").css("background-color", "purple");
Now when you run this code, the Navigation Div should turn to purple.
If you want to update multiple CSS properties, you can add them all together like this:
$("div#navigation").css({
"background-color": "purple",
color: "yellow",
"font-weight": "bold",
});
The method for using multiple CSS properties at the same time is known as a Javascript Map. A Map is a series of Key, Value pairs that are separated by a colon. If you’ve worked in just about any other programming language, you will be very familiar with this structure.
If you haven’t, a map is probably easier to understand displayed like this:
{
"background-color":"purple",
"color":"yellow",
"font-weight":"bold"
}
So the bit on the left of the colon is the Key, and the bit on the right is the Value. This is a common data structure for handling multiple bits of data.
As you can already see, changing individual CSS properties on elements is incredibly tedious and something you are unlikely going to be doing in real life. Adding or removing classes however, is something that you might need to do from time to time.
As a general rule, your CSS should handle all the styles of your web page, you shouldn’t really be using jQuery to do too much with style. Instead, use jQuery to trigger Classes and Ids that have related style information from the CSS. This is a much cleaner separation of concerns.
So for example, say we wanted to manipulate the last Navigation item to show that it was the active item, we could do this:
$("div#navigation ul li:last").addClass("current");
Similarly, to remove a class, we can just use the removeClass function:
$("p#introduction span").removeClass("more");
If you wanted to remove all the classes on an element, but you don’t know the name of the classes, you can still use the removeClass function, just don’t pass any arguments:
$("p#introduction span").removeClass();
A lot of the time in jQuery, you want to switch between two different states, rather than explicitly going from one to the other. The toggleClass function will either add or remove a class depending on if that class is already set, or not.
$("p#introduction span").toggleClass("more");
If you run the code above over and over again in the Console, you will see the class being added and taken away. This is much more useful than simply adding a class or removing it.
Another common technique in web design is the ability to show or hide elements on the screen. For example, you might want to hide something after a user takes an action.
To do this we can use the hide function:
$("p#conclusion").hide();
To show it again, just use the show function:
$("p#conclusion").show();
And like the toggle class function, we can also toggle between the two states, independently of what they currently are:
$("p#conclusion").toggle();
As you can see from the output of the console, the show, hide and toggle functions simply add the CSS property “display: none” to your element, so it doesn’t actually go anywhere, it just becomes hidden.
If you save any of these code snippets into a file and reload your page, you will notice that they seem to lose their ability to work.
When you structure your page like this…
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="my-jquery-scripts.js"></script>
html stuff...
</html>
All of your jQuery code will be run before any of the HTML is loaded into the DOM. This means that if you are trying to manipulate an element, the jQuery will try to manipulate it before it is even on the page.
To solve this problem, we need to wrap out code around a Document ready block. If you have ever looked at jQuery example code, you will often see it in this format.
$(document).ready(function () {
$("div#navigation").css("background-color", "purple");
});
What this does is, it waits till the page is loaded, then it runs the jQuery. This ensures that the elements you are trying to manipulate are correctly loaded first.
Manipulating the CSS elements is only really scratching the surface of what is possible with jQuery, but it is important once you start to build interactive websites.
Websites have evolved over the last couple of years and now users expect engaging experiences right inside the browser. jQuery is an important first step to understanding how to build these kind of experiences.
Come back soon as we look at more of what can be achieved through jQuery.