Introduction to jQuery
This screencast will show you how to use some of jQuery’s core functionality, including accessing attributes, manipulating HTML, transversing the document, applying effects and handling events. We’ll show you how to setup a page with an article and two forms (sign in and sign up) that dynamically hides and reveals the forms, and compares the password and password confirmation fields, along with notifications for the user.
What You'll Learn:
- How to access attributes
- How to Manipulate HTML
- How to Transverse the document
- How to apply effects
- How to handle events
A little web development history...
To fully appreciate jQuery, let’s quickly review some web development history:
Back in the early days of the web, people used tables and in-line styling such as the font tag to build websites.
This made it difficult for search engines and screen readers to navigate the html markup.
More recently CSS evangelists started telling us we should have a separation between markup and layout. This enabled web developers and designers to build the same webpage with separate styling and cleaner markup.
This had a number of benefits. It improved the experience for screen readers and search engines, but it also reduced load time with smaller html files and styling in only one file. This also made websites more manageable.
CSS enables us to describe our documents layout by assigning classes to elements. We can use this technique to apply behavior to elements in an efficient manner. The best practice would be to add a descriptive class (such as "new_window”) to our link.
First we need to apply the functionality when the document loads.
Then we need to iterate through the document’s anchors or links, looking for our "new_window” class.
The reason we are getting elements by tag name, and then checking the class, is because some older browsers such as IE6 don’t have the method
getElementsByClassName, so we have to cater to the lowest common denominator.
Once we’ve found the link in question, we need to add the desired functionality:
But this code is far from perfect. There are a number of problems. The
window.onload handler gets executed after the page and any images have loaded. This means your application may not look as desired until the browser has finished loading the assets. This code overrides any existing load or click handlers, which could be in conflict with other behaviors. This could be a problem if you’re working on a project with two developers, and you’re both applying behavior the same link. If this were the case, the last behavior executed would win.
The way we are checking for the classes applied to our links is very brittle. It wouldn’t work for links with more than one class applied to it. For example, our code wouldn’t work for a link with a class attribute
onready handler which executes when the html file is downloaded, but the images haven’t. The
As you’ll see, jQuery allows you to write less code, and do more.
Using jQuery in Your Projects
When you download the "Production” version of jQuery you’ll notice that the size of the file is not 24KB it’s around 70KB. This is not a mistake. The jQuery minified version is actually not 24 KB but 70KB. However if you go back to jQuery.com the "Production” version doesn’t just say minified, it also says gzipped.
Once you’ve downloaded the version of jQuery you want or found the URL from Google, all you need to do is include the jQuery file in your html somewhere.
This can be done in two places:
It looks like this:
When the HTML document has loaded and is ready to be manipulated by jQuery the anonymous function or handler gets executed and the code is run.
Or in short hand:
You can remove
(document).ready and it will still work. Either way is acceptable.
The second way of including jQuery is at the bottom of the page, just before the closing body tag. But this time you don’t need to use the ready event because the page is already downloaded and is ready to be manipulated.
So now it looks like this:
This way is recommended to increase page load speeds giving users a better experience.
As you can see with both ways of including jQuery, the paragraph tag gets populated with the text "Hello jQuery”.
Now lets move on to the main code example.
Here is an example web page with two forms and an article.
This code for this example is available in the show notes.
In this example we’re going to cover how to hide the forms when the page loads, setup jQuery functions to reveal the appropriate form when a link is pressed, and show some basic validation on the form. You’ll learn now to select, manipulate and transverse your html document using jQuery. So let’s get to it.
Open the index.html file in your browser. As you can see, we have two links, sign in and sign up. They link to their respective forms. Open the index.html file in your editor of choice.
As you can see we have two links in an unordered list, followed by two forms, sign in and sign up, and then an article.
The forms are very basic, with a small number of fields. If you’d to familiarize yourself with the html, feel free to pause the video at this point and review the code.
Obviously, showing the two forms on the page like this isn’t desirable. Let’s use jQuery to hide the forms. First we need to add jQuery to our page, then create an application.js file and include that file in our document.
So let’s add
className=”forms" to each of the form divs.
Because we are including application.js at the end of the file, we don’t need to manually add the onready callback. All we need to do is put in the jQuery behavior we want to be executed as soon as the file is loaded.
To hide the forms, we simply add
$(".forms").hide(); to our application.js file.
As you can see, when we refresh the page in our browser, the forms are now hidden. When we click on these links however, nothing happens. We need to add the behavior to reveal the forms.
We need to add a click event listener to the link elements contained within the unordered list and list items. In order to check that we are correctly binding this function to the link elements, let’s add a simple alert to verify.
In the function,
this refers to the DOM element in which the click handler has been triggered. In order to get the jQuery representation of the DOM element, we need to enclose
this in parentheses with a dollar sign in front of it. Now that we have a jQuery representation of the object, we can now use jQuery methods on it. The
attr method can be used to access the value of a given attribute. In this case,
So let’s check this out in the browser to see if it’s working correctly. Ok, great, clicking on the links gives us the desired executed code. If you notice, the hash link is also exactly the same as the CSS selector for the relevant form’s container. So let’s now select that using jQuery, and use the jQuery show method in order to reveal it. For the sake of convenience and readability, we will create a local variable idToShow. Then we need to get a jQuery representation of the element with that id by adding the jQuery parentheses around idToShow. We then add
.show(), and as you can see it shows the correct form.
But if you notice, when we click the other link, it now shows both of the forms. Ideally, we’d want the other form’s container to hide. In order to do this, we create a local variable "siblings” and assign it
$(idToShow).siblings(). On the next line we write
siblings.hide(); in order to hide the siblings.
If we launch this in the browser now, we’ll see that when we click on a button, the entire page is hidden apart from our selected form. This obviously isn’t what we want, so let’s go back to our .js file and be more specific in the siblings that we want to hide. So within the siblings function, we can pass in the CSS selector we want to hide, in this case ".forms” .
Thinking back to our decision to use a class "forms” to identify our form containers, this has made this a trivial exercise. If we just used the ids of the containers, we would have to implement a much more complex method to hide the form containers.
Now that we’ve added the
.forms CSS selector to our siblings function, we can see in our browser that the desired functionality of hiding the other form is working. But the browser is jumping to the top of each form container when clicked. To prevent this, all we need to do is add
return false to the end of our function, which overrides the default browser behavior for a link.
jQuery enables us to chain methods together. So these lines can be written in fewer lines. At the end of the show method, we can add
siblings(".forms") followed by
.hide(). What this is doing is getting the siblings of the container we want to show, and hiding them.
Now lets add a way to notify the user when the password fields don’t match. To do this we need to add a jQuery event listener to our password confirmation field. We need to watch for key strokes on the field and compare it with the first password field. The
keyup event is triggered after the key is pressed. Once again we need to implement an anonymous function to be triggered on keyup. On any type of input you can call
val() to retrieve the value of that particular input. So here we need to see if the two passwords match or not. If they don’t match we’ll add a CSS class called
error to notify the user. It could be named anything, we’re just using something sensible.
We need to remember to add some styling in our CSS to alert the user.
So now when we type
test in to our password field and
test1 in our confirmation we see the error class being applied. Great. But this isn’t quite complete because when we correct the password field the
error class isn’t removed.
To do this we just need to include an else statement to remove the error class when it matches. Simple.
Here we can see that when the fields match, the error class is being removed correctly.
Finally we want to include a text message to say that the passwords don’t match. First lets add an empty span tag after our confirmation input in the HTML. In order to get the span from the confirmation field we can transverse, or move through the document by using the
next() method. This will return the span element for you to manipulate. All we need to do now is add the
text() method to the returned span with the strings we want it to display. So we’ll display "Passwords don’t match” when they don’t match, and an empty string
"" when they do match. Again we’re chaining methods together, but this could be written over many lines. But chaining methods like this makes the code much easier to read.
Hit refresh and we have our fully working example.
In this jQuery introduction we’ve covered several main areas: accessing attributes, manipulating html, transversing the document, applying effects and handling events.
Thank you for your time and we hope you’ll have fun putting your new skills to use.
If you have any questions, feedback or suggestions please email firstname.lastname@example.org.