Lesson 19: Short Introduction to jQuery
By Maria Antonietta Perna
However, this is a wide topic and these 3 lessons cannot but give you just a taste for what jQuery can really do.
Therefore, I encourage you to visit the jQuery website after you finish this tutorial, and explore and experiment with jQuery's numerous methods, events, effects, etc., for yourself.
In this lesson you will learn:
about the benefits of using jQuery;
how to include jQuery in your project;
about jQuery selectors to manipulate DOM elements in code;
how jQuery handles events;
how to use anonymous functions with jQuery;
how to add and remove DOM elements with jQuery.
Why should I use jQuery?
- extremely light-weight (just 31 kb in its latest minified and zipped production-ready version);
- it's free and very easy to include in your projects: just download its latest version from the jQuery website, or use an online Content Delivery Network;
- it's continually upgraded, maintained and documented by a dedicated community of great developers. This ensures high quality and support on the internet;
- and last but not least, it offers a wealth of ready-made animation effects that are a joy to use.
How do I include jQuery in my website?
Including jQuery in your project is fast and easy. You have the choice of downloading a copy of the library and save it locally, or you can use a Content Delivery Network (CDN) to serve jQuery to your website on the Internet.
Go to the jQuery website download page
How to include a local copy of jQuery
If you prefer having a local copy of jQuery:
go to the Download jQuery section of the download page and click on the minified version of the latest release of jQuery. At the time of writing this is version 1.7;
- copy and paste the code in a text file;
- save the file in your web project directory (better if you save it in its own subfolder);
- in your html page include the appropriate <script> tags in the following order:
<title>Lesson 19: Introduction to jQuery</title>
<h1>Lesson 19: Introduction to jQuery</h1>
How to include a hosted copy of jQuery
If you decide to opt for a CDN to serve up a copy of jQuery to your website, then follow these easy steps:
go to the CDN Hosted jQuery section of the download page and pick one of the different CDN services available;
copy the URL of your CDN of choice and paste it as the value of the <script> tag's src attribute, like so:
That's it, you're done!
How to make sure jQuery is working
Now the jQuery library can be used in your project. To make sure things work as expected, create a text file and call it jquery_test.js. Enter the following code:
alert("jQuery is working!");
Save all your files and run the HTML page in a browser. If you typed the code exactly like the example above, you should be greeted by ... well, the good old alert box.
How do I access DOM elements using jQuery?
jQuery appeals so much to web designers also because it enables us to select DOM elements in code just like we do with CSS. Let's see it in action.
Select html elements by id
Remember our old document.getElementById()? Well, jQuery makes selection by id much shorter. Here's how it's done:
var myDiv = $("#myDiv");
The $ sign in front of ("#myDiv") can be translated like: "Hey, browser, get me the element with the id of myDiv!"
As you can see, the id attribute is grabbed by using the # sign, the same as CSS.
Select html elements by tag name
You also came across document.getElementsByTagName(). This method allows us to grab all html elements by their tag.
Look how jQuery makes it a lot snappier:
var images = $("img");
As you can see, the magic $ does most of the talking.
Select html elements by class name
A quick way to target html elements that share the same class is as follows:
var redElements = $(".classRed");
Now redElements contains an array of all the html elements on your page with a class of classRed.
Once again, notice how jQuery facilitates selection by using the same notation you use in your CSS declarations to target classes: .className.
Select html elements using jQuery filters
jQuery enables you to be as precise as a surgeon when targeting html elements and attributes on the page. jQuery offers a filtering syntax to query the DOM that is both simple and efficient.
Here's a list of the most common filters:
The first item in a matched set
$(‘p:first’) returns the first paragraph.
The last item in a matched set
$(‘p:last’) returns the last paragraph.
The odd-indexed items in a matched set
$(‘tr:odd’) returns table rows indexed at 1, 3, etc.
The even-indexed items in a matched set
$(‘tr:even’) returns table rows indexed at 0, 2, etc.
finds elements having the child element specified
$(‘p:has(span)’) returns all paragraphs containing a span element.
returns the element with the matched index
$(‘p:eq(1)’) returns the second paragraph starting to count at 0.
Returns all elements containing the text x
$(‘div:contains(foo)’) targets all divs with the text 'foo'.
A complete list of all selection methods and filters is available on the jQuery website. Have a look and experiment with the available code samples to gain more familiarity with the new approach.
How do I assign event handlers using jQuery?
Event handlers are code blocks, usually functions, that specify what your application should do when a specified event like, for example, a button click, occurs.
So far, you've used 2 approaches:
hard-wiring a function to the html element itself:
<input type="button" onclick="doSomething()" />
assigning a function to the DOM object's appropriate property:
myElement.onclick = doSomething;
The second approach complies with the separation of concerns principles, but comes short in case we want to attach more than a function to the same element.
There's actually a third approach that overcomes all shortcomings but one: it's implemented differently in Internet Explorer browsers with respect to all other major browsers.
The good news is: jQuery is here to make event handling quick and easy. Here are a few jQuery approaches to choose from.
The bind() method
bind(eventType, handler) works as follows.
Suppose you have an html element with an id of myElement, and a function called sayHello(). You want sayHello() to kick in when the user clicks on the html element. This is how you achieve this using bind():
You can find more details on the bind() method on http://api.jquery.com/bind/.
The ready-made approach
Binds a handler to an onclick event.
Binds a handler to the onmouseover and onmouseout events.
Binds a handler to the onchange event (when the content of a field changes).
Binds a handler to the onselect event (when text is selected).
Binds a handler to the onsubmit event of a form element.
Binds a handler to the onfocus event (when an element gets focus).
Binds a handler to the onkeypress event (when a key on the computer keyboard is pressed).
Assuming you have an html element with an id attribute of myElement, and a function called sayHello() - as in the previous example - you can bind sayHello() to the onclick event of myElement inside jQuery's ready() function like so:
The on() method
With this latest version of jQuery (v.1.7), a brand new method to handle events has been introduced.
The on() method is highly recommended by the jQuery team if you start a new project.
It can be used to attach handlers both to elements already present in the HTML page from the start and on dynamically added elements (unlike bind()). Here's how it's used.
Using the same sayHello() function, inside jQuery's .ready() function simply write:
More details on the on() method can be found on http://api.jquery.com/on/.
Code samples using jQuery often employ anonymous functions. These are functions without a name, and can be quite handy, although I find names more helpful in terms of code readability. If we replace the sayHello() function with an anonymous function, we have:
Add and remove DOM elements
You've had a taste of standards-compliant DOM manipulation techniques in this tutorial. Therefore, you will readily appreciate the jQuery way of performing the same tasks.
Add new DOM elements
You can both retrieve html elements and add new html elements to the page using jQuery's .html() method. When you don't pass any arguments, html() retrieves a DOM element, if you pass a string argument, html() adds that string to the page.
If you just need to add new text inside an html element, you can use jQuery's .text() method and pass a string argument representing the text you intend to add. Like .html(), you can use .text() without passing any arguments to retrieve text content from the HTML page.
To test .html() prepare an HTML page containing a <div> tag with an id of myElement, a <p> tag and some text. First we retrieve the existing paragraph element, then we create a new paragraph.
var pageParagraph = $('p').html();
var newParagraph = $('#myElement').html('<p>Hello new Paragraph!</p>');
//close off all your brackets:
Save all your files and preview the result in a browser. The alert should display the original paragraph's content, and the page should subsequently display the new paragraph's content.
The way you implement .text() is the same as .html(). I leave you to experiment with it on your own. More details on .html() can be found on http://api.jquery.com/html/, and on .text() can be found on http://api.jquery.com/text/.
Remove DOM elements
A simple way of doing this is with jQuery's remove() method. Let's put it to the test.
Use the same HTML page from the previous example and add a button element with an id of btnDelete.
Save all your files and preview the HTML page in a browser. Click the button and see the paragraphs on the page disappear.
More on .remove() can be found on http://api.jquery.com/remove/.
There's a lot to digest in this introduction to jQuery and you've done a great job coming as far as you did.
jQuery is such a rich library that it can't be covered in a few lessons. Therefore, I invite you to practice with all the code samples in this lesson and the following lessons as much as you can.
Also, it's crucial that you explore the jQuery website and experiment with the code samples available in their documentation and tutorials. If you have doubts, don't hesitate to send us a line in the forum dedicated to this tutorial.
More on jQuery coming up in the next lesson: get ready for some fabulous JQuery effects in just a few lines of code!
Related topics in the
|No related topics yet|
+ Post a new topic
<< Lesson 18: Making AJAX Calls
Lesson 20: Cool Animation Effects with jQuery >>