JQuery Notes – CTP 136 – Getting Started with JQuery

jQuery’s purpose is to make JavaScript easy to use by hiding complex JavaScript code within easy to use jQuery methods.   These methods are pre-built and ready to use.  Furthermore, jQuery methods have cross-browser support already built-in.  Simply put, jQuery is a JavaScript library.

jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.

JavaScript is included in an HTML document within the tag. The tag is container tag meaning that there are two tags, a beginning tag of and an ending tag of .   When the browser encounters the tag, the browser’s scripting host is activated and the JavaScript code is interpreted and executed.  The scripting host continues until the tag is encountered.  Only JavaScript is allowed between the and tags.  No HTML code may appear between the and tags.  The tag also defines a src attribute, which allows JavaScript code stored in an external file to be imported into the document.  The external file should only contain JavaScript code and should have an extension of .js.  There should be no HTML in the external file.

The jQuery library is contained within an external JavaScript file.  The HTML document will reference either a local copy of the file or a copy stored on the Web using the tag and src attribute of the tag.  For this class, we will utilize a local copy of the library.

We will develop custom jQuery code which will utilize the jQuery library.  This code is placed within an additional tag.  Often, this code is also placed within an external file and added to the page using the src attribute of the tag.  This is the approach utilized in this class.

The order in which the files are specified is very important.  The CSS file which defines many classes and identifiers is usually specified first.  The jQuery library follows.  Lastly, the custom jQuery code is specified.  Because a Web page is interpreted top to bottom, the jQuery library must precede the custom jQuery in order to use the library routines.

HTML code Description
Link to CSS file named styles.css
Includes a copy of the jQuery library
http://mycode.js Custom jQuery code contained in a file named mycode.js

 

Prior to developing the jQuery code, be certain that the Web page displays as intended and is styled as desired.

Any plain text editor such as NotePad++ may be used to create and edit the custom jQuery file.

Accessing Web page elements

We use jQuery and JavaScript for interacting with the end user and modifying Web page elements.  We may want to modifying elements of the Web page to change their appearance, change their content, to animate the element, and/or modifying the element’s behavior.  In order to modify an element of a Web page, we must first obtain a reference to the object that represents the element.  With a reference to the element, we can modify it’s properties and call it’s methods.

In CSI 117, we defined classes, specifying attributes (also called characteristics, data members, or properties) and methods (code which defines behavior.)  Using the class definition, we created instances (objects) of the class.  When an instance is created, a reference to where the object is stored in memory is returned.  Using dot notation, this reference allows us to access the object, retrieve or set its attributes and call its methods.  The following syntax is used for dot notation:

        reference.attributeName

        reference.methodName(parameters)    // Parenthesis are required.  Parameters are contained within the parenthesis with multiple parameters separated by a comma.  Some methods have no parameters while others have one or more.

For example, if we define a class named College with a public attribute of name and a method called about, we can use the following pseudo code to create an instance, modify the name attribute and call the about method:

       myCollege = new College();     // create an object and obtain a reference to it

       myCollege.name = ‘AACC’;      // using the reference to the object, change the name attribute

       myCollege.about();            // using the reference to the object, call the about method.

In the above pseudo code, we created the object and stored the reference to the object in a variable named myCollege.  In a Web browser environment, most objects that we will work with will be created for us when the Web page is loaded.  Therefore, we only need to obtain a reference to the object.  The $() jQuery function is used for this purpose. The function accepts a parameter identifying the element(s) to search for and returns a reference to the element(s).  For those with JavaScript background, this is similar to the getElementById method of the document object.

Basic syntax for all jQuery methods:

       $(selector).methodName(parameters);

where $ denotes that what follows is jQuery.  (selector) is a string used to locate HTML elements that we want to act on.  methodName is the jQuery method name that we’d like to apply to the selected elements.  Some methods require one or more parameters while other methods require none.  When more than one parameter is coded, they are separated by a comma.

Suppose we have a paragraph on our page with an id attribute value of ‘p1’.  Recall that the id HTML attribute allows us to uniquely identify an element.

       <p id=”p1″>This paragraph is displayed in italics!</p>

When the page is loaded, an object representing the page element will be created.  Along with this object are various attributes such as the style attribute.  Using JavaScript, we use the getElementById method of the document to obtain a reference to the ‘p1’ object and then change its style attribute.  Likewise, we can use the jQuery $() function to obtain a reference to the ‘p1’ object and the css jQuery method to change the style.  Notice how a # precedes the id in the jQuery statement.  This is identical to how a style is applied to an id in a style sheet.

JavaScript statement
     document.getElementById(‘p1′).style.fontStyle=’italic’;  // change the style attribute

jQuery statement
$(‘#p1’).css(‘fontStyle’,’italic’);                      // call the css method

Although the above doesn’t represent much of a savings in the amount of code or complexity over JavaScript, consider any of the following jQuery calls.  Notice how each follows the basic jQuery syntax with each method requiring zero, one or more parameters.

       $(‘#p1’).hide();
$(‘#p1’).fadeTo(‘fast’,0.5);
$(‘#p1’).slideDown(‘slow’);

In chapter two, we’ll learn more about using CSS selectors as well as jQuery custom selectors as a parameter to the $() jQuery function.

Comments may be added to the code contained in the .js file.  Comments are ignored by the JavaScript interpreter but allow us to insert notes or prevent statements from being executed.  The // symbols indicate that all remaining characters on the line should be ignored.  To add a comment that spans more than one line, the /* and */ symbols may be used.  All characters between /* and */ are ignored by the JavaScript interpreter.

     /* The statements below demonstrate comments.
This paragraph is a multi-lined comment and is ignored by the interpreter.
Any characters that follow the // symbols are also ignored. */

     // Only the last portion of the following line is ignored
$(‘div.poem-stanza’).addClass(‘highlight’);      // Add the highlight style class

     // The entire line below is considered a comment
// $(‘div.poem-stanza’).addClass(‘lowlight’);

The Good, the Bad, and the UGLY

As a Web page is interpreted, objects are built and the page is rendered in memory.  Once completely interpreted, the page is displayed.  The problem with this technique is in the placement of our jQuery statements.  We need the objects created before we can reference them, but we often want to make our changes before the page is displayed.  Even when our code is not display oriented, we need to establish the functionality before the page is displayed to the end user.

The way we can make sure that the objects are ready to be referenced is to delay executing code until the document has been deemed ‘ready’ by the browser.  And, leave it to jQuery, we have a method for that!  The method name is ready() and the object it is associated with is the document.  The document reference is predefined for us (no need to use a CSS selector.)

          $(document).ready(jQuery function here);

The ready method follows the same syntax as all jQuery.  Notice however that document is NOT contained within quotes since this is a predefined variable.   For those with JavaScript background, the ready method is similar, but not equivalent to the onload event of the document.

Most of the code that we write will be contained within a function.  A function defines a set of statements which will be executed when the function is called.  A function is similar to a method but is not associated with a particular object.  Like a method, a function may be passed parameters which are enclosed within parenthesis and separated by commas.  Parenthesis are always required, even when no parameters are passed to the function.

The basic JavaScript function definition syntax is shown below.  Note the parenthesis that follow the function name.  They are always present and are used to enclose the optional parameters.  The statements of the function are contained within brackets { and } which are also required.

        function functionName() {
            // statements here
        } // end of the function

Once a function has been defined, it can be called at any time.  It may also be called from multiple locations.  In the example below, the function is called as soon as the page is ready.

  function changeToItalics()  {            // function definition (code NOT executed until function is called)
      $(‘#p1’).css(‘fontStyle’,’italic’);
   }

  $(document).ready(changeToItalics);      // call the function when the page is ready

Often, especially when using jQuery, we have a set of statements that are performed once or the statements are very short.  Rather than creating a named function, we create an unnamed or anonymous function to perform our work.  The function in this case is not reusable.

An anonymous function does not have a name.  All other syntax elements, parenthesis and brackets must be present.  An anonymous function may be embedded anywhere a function call is expected.  For example, since the parameter of the ready method is a function, we can use an anonymous function as the method parameter.  Notice the syntax below where an anonymous function has been inserted as a parameter to the ready method.

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

The above is usually written on several lines, separating the statements of the function from the rest of the function definition syntax:

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

Therefore, the completed jQuery code to change the ‘p1’ element to italic after the page is loaded is:

  $(document).ready(function () {
     $(‘#p1’).css(‘fontStyle’,’italic’);
  } );

Be careful when writing anonymous functions.  It is easy to overlook one or more of the required parenthesis, brackets, and/or semicolons!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: