Web Development

How to get started with jQuery

Ryan Boudreaux shows you how to get started using the cross-platform JavaScript library jQuery in this tutorial. You will need a knowledge of HTML and CSS and a basic understanding of JavaScript.

Getting started with jQuery is not a difficult task; in fact, it's much easier than writing your own JavaScript code. However, it too does take some practice to get the feel of how to use it to take web documents to dynamic content.

jQuery is a new kind of JavaScript Library. Fast and concise, it simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. In addition, jQuery is designed to change the way that you write JavaScript, it has a lightweight footprint, is CSS3 selectors compliant, and is cross-browser supported.

This tutorial series on jQuery will give you the foundations to understand and practice these elements:

  • "ready()" event function
  • get an object by ID, class, tag, and attribute
  • filtering objects
  • change CSS classes
  • change an object's text
  • change appearances of content to expand and contract with the hide function
  • create an expandable and contractible FAQ template

So, what tools or skills will you need to complete this tutorial series? You will need a good understanding of HTML and CSS, a very basic knowledge of JavaScript, and a willingness to learn new coding techniques.

I will be using Dreamweaver to code the example HTML documents, but any text editor that works for you is fine. All HTML documents including script and styling files used in this tutorial can be found in the download.

Putting down the foundation

We will use an HTML5 doctype as a basic template for our tutorial; you can find it in the download or copy the code listed below into a new blank HTML document, which we will name index.html. The tutorial web directory structure as in the download is set up with the following:

  • web\ - contains index.html and styles.css
  • web\scripts - contains jquery.js
  • web\images - contains image files
HTML code:
<!DOCTYPE html>
<html lang="en">
 <head>
    <meta charset="utf-8">
    <title>jQuery Tutorial</title>
 </head>
 <body>
   <!-- HTML -->
   <!-- Scripts -->
   <script src="scripts/jquery.js"></script>
   <script>
    // JavaScript
   </script>
 </body>
</html>

If you open the index.html file or copy the code above you will find a blank page, of course you can see that the body contents are empty with the exception of calls to scripts including the scripts/jquery.js. The jQuery download is the current release version 1.7.2; it is the minified version that comes in at just 93KB file size, and is the recommended version of jQuery to use for your applications. The minified and gzipped compression version is just 32KB. The code in this jQuery file should be stable and usable in all modern browsers. Check for the latest version of jQuery, choose your compression level, and click to download.

TIP: You might have noticed that the calls to the scripts and the script tags are all at the bottom and just before the closing body </body> tag. If you have not started, moving your script tags to just before the closing body tag, you might want to consider the change. Not only does it speed up your page load times, but should anyone have JavaScript disabled or turned off, it will not cause problems with the web document until everything else has already loaded into the browser.

Let's set up some more of our foundation so that we have something to work with as we start to play around with jQuery. First, let's add in some content within the <body></body> of the web document.

The HTML code shown below creates two articles, one with the text Article No class No id, and the other article with the text Article class="test" id="two. There is also a nested section with the text Section class="test" No id, and below that is a paragraph with the word Switch.

   <section id="content"><p>Section id="content"</p>
      <article>
        <p>Article<br />No class<br />No id</p>
      </article>
      <article class="test" id="two">
        <p>Article<br />class="test"<br />id="two"</p>
      </article>
      <section class="test">
        <p>Section<br />class="test"<br />No id</p>
      </section>
   </section>
   <p><strong>Switch</strong></p>

Save your index.html file before you create the new styles file. The following styles are added to a new CSS file, which we will create and name styles.css and save into the root web folder. The styles will create a solid blue border for the three boxes with a 10px border radius, a box shadow effect, with height and width of 200px, left padding of 15px, a bottom margin of 10px, and a left margin of 10px. The paragraph content is styled to the Tahoma, Geneva sans-serif with a 16px font. The "#content .newClass" style shown below will be incorporated in the next installment of the series:

@charset "utf-8";
/* CSS Document */
#content section, #content article {
       border: 2px solid blue;
       -webkit-border-radius: 10px;
       -moz-border-radius: 10px;
       border-radius: 10px;
       display: block;
       float: left;
       height: 200px;
       width: 200px;
       padding-left:15px;
       margin-bottom:10px;
       margin-left:10px;
       -webkit-box-shadow: 4px 4px 5px rgba(118, 100, 26, 0.56);
       -moz-box-shadow: 4px 4px 5px rgba(118, 100, 26, 0.56);
       box-shadow: 4px 4px 5px rgba(118, 100, 26, 0.56);
}
#content .newClass {
       width: 200px;
       height: 100px;
       border: 2px solid green;
}
p {
       clear: left;
       font-family:Tahoma, Geneva, sans-serif;
       font-size:16px;
}
input {
       display: block;
}

Save your styles.css and add the following code inside the <head> tag of your index.html file:

   <link rel="stylesheet" href="styles.css" type="text/css" media="screen" />
Then open the index.html file and reload it in your browser to view the boxes with shadow effect. Figure A shows our index.html file looks now as viewed from Chrome 17.0.9:

Figure A

The jQuery "ready()" event function

To use the power of jQuery you need to set the ready event, as all jQuery code is contained within this function and is executed when a web document is fully loaded or "ready", in other words jQuery has a simple statement that checks the document and waits until it's ready to be manipulated, which is known as the ready event. The jQuery "ready()" event function starts with adding the following code within the <script> tags which we commented for the JavaScript in our index.html document.

        $(document).ready(function(){
               // Your code here
       });

Now, let's put an event handler to work. Next, we will add in this anchor reference as part of the paragraph of the first article as illustrated below:

      <article>
        <p>Article<br />No class<br />No id<br />
         <a href="http://docs.jquery.com/Main_Page">jQuery Documentation</a></p>
      </article>

Then, inside the event handler add the following code:

$("a").click(function(event){
         alert("Thanks for visiting the documentation!");
       });

The entire event handler code should now look like the following:

   <script>
    // JavaScript
        $(document).ready(function(){
               // Your code here
        $("a").click(function(event){
          alert("Thanks for visiting the documentation!");
        });
     });
   </script>
Save the index.html file and reload the document in your browser. Clicking the link on the page should make your browser's JavaScript alert pop-up, displayed in Figure B below.

Figure B

Click OK on the pop-up and it takes you to the jQuery Documentation page, as shown in Figure C:

In following parts of this jQuery series, I will cover getting an object by ID, class, tag, and attribute; filtering objects; changing CSS classes and object text; using the hide function to make content appear to expand and contract, and creating an expandable and contractible FAQ template.

About

Ryan has performed in a broad range of technology support roles for electric-generation utilities, including nuclear power plants, and for the telecommunications industry. He has worked in web development for the restaurant industry and the Federal g...

4 comments
pbcoolhand
pbcoolhand

For some reason, I never see the alert box message before being redirected to the anchor tag href. This is true even when I copied and pasted your code to my text editor.

RJBoudreaux
RJBoudreaux

Justin, Good question! This is just a simple example, and in this demonstration the jQuery is calling for all anchor tags $("a"), which in this case there is only one in the index.html file. jQuery() which can also be written as $() searches through the DOM for any elements that match the provided selector and creates a new jQuery object that references these elements: i.e. $('div.foo'); jQuery selectors can be used to select any tag <body>, <article> <a>, etc... In the next segment we will demonstrate "Get Object by jQuery ID Selector (#id)" However, if you wanted to create specific id's for each anchor tag you could add the id="doc": <a href="http://docs.jquery.com/Main_Page" id="doc">jQuery Documentation</a> And then set the jQuery to: $('#doc').click(function(event){ alert("Thanks for visiting the documentation!"); Which would assign all objects with the id="doc" to display the pop-up message. In the case below, each anchor tag when clicked, would generate it's own pop-up message: <a href="http://docs.jquery.com/Main_Page" id="doc">jQuery Documentation</a> <a href="http://www.google.com" id="google">Google</a> $(document).ready(function(){ $('#doc').click(function(event){ alert("Thanks for visiting the documentation!"); }); $('#google').click(function(event){ alert("Thanks for visiting Google!"); }); });

Justin James
Justin James

$("a").click(function(event){ alert("Thanks for visiting the documentation!"); }); Obviously, this is binding an event handler to an object. But *what* object is it being bound to? There's nothing in the example with an ID of "a", so is it being bound to all "a" tags? If so, is that really the behavior we want? If not, how do we write the code to actually apply specifically to the documentation link? J.Ja

Justin James
Justin James

OK, I was afraid I overlooked something. This makes sense, thanks! I am looking forwards to the next entry, since I have had "learning jQuery" on my todo list for a long, long time now. J.Ja