CodingBison

This page uses a simple jQuery program as a basis to go over some of the important syntax-rules and guidelines for writing jQuery applications.

In terms of running a jQuery program, we need to do roughly three things.

First, we need to use the HTML script tag to source the jQuery library. If the jQuery library file were to be "jquery.js" and this file were in the current folder at the webserver, then we can do so as: '<script type="text/javascript" src="./jquery.js"></script>'. We need to source the jQuery library prior to having the script tag that holds the actual code. Of course, the popular option is to include an existing jQuery from a well-known CDN. For example, we can include Google's jQuery CDN as follows:

  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">

Second, we need to embed the jQuery code in an HTML page using the same script tags "<script type="text/javascript">" and "</script>". This time using the "src" attribute is not a must. Any code that sits between these two tags executes in the JavaScript context. And, since jQuery runs on top of JavaScript, we can embed jQuery code as well. We can place jQuery code anywhere in an HTML page and we can place it any number of times.

Third, we need to call jQuery APIs using jQuery() method. A method is set of code that does a specific task and can be reused. The popular and convenient way to call jQuery method is to use its shorthand method: $(). Thus, instead of writing "jQuery(x)", it would suffice to say, "$(x)". Even simpler!

Now, you might say that some JavaScript libraries may already be using "$" as a shortcut to other symbols. Well, for such cases, jQuery provides the noConflict() method. When invoked (as in "$.noConflict()"), this method removes the aliasing of jQuery() to "$()". Beyond this point, one must explicitly use "jQuery()" and not "$()".

Since jQuery library runs on top of JavaScript, it is almost certain that your program would also contain some amount of base JavaScript code. The good news is that since JavaScript is run using the built-in JavaScript interpreter, there is no need to compile jQuery programs since we do not compile JavaScript programs! However, this does not mean that you can get away with compilation errors since your program might still contain them. And if that is the case, then you would still need to fix them. One way to fix such errors is to use the Firefox's Firebug plug-in!

We begin by providing below a simple jQuery example that does a little more than printing "Hello World". This programs prints "Hello World!" and also uses a button to change the color of the text. When the user clicks the button, it changes the color to blue. We can keep this code in an HTML file (let us name this file, "jquery_hello.html").

 <!doctype html>
 <html>
 <!-- Let us start by including the jQuery library -->
 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
 </script>

 <body>
 <!-- Add a div element with CSS ID as "idDiv" -->
 <div id="idDiv"></div>

 <!-- Add a button with CSS ID as "idButton" -->
 <button id="idButton">Change my color!</button>

 <script type="text/javascript"> 
     jQuery(document).ready(function() {
         // Write something to the div element.
         jQuery("#idDiv").append("Hello World!");

         // Set the event-handler for the click event.
         jQuery("#idButton").click(function() {
             $("div").css("color", "blue");
         });
     });
 </script>
 </body>

 </html>

Before we go any further, let us take a note of few additional things.

As started earlier, the HTML page has two sets of script tags. Both of them are of type "text/javascript". The first one uses the "src" attribute to link the jQuery library from the Google Server to this page. We can find more information on Google jQuery library here: https://developers.google.com/speed/libraries/devguide#jquery .

The example includes the version 1.9.1 of the jQuery library. This is essentially version 1.9 and subversion 1. Sub-versions typically contain important bug-fixes. The jQuery library include contains the library file "jquery.min.js" which is actually a minimized version of the library. Since the file is minimized (compressed), it is more efficient for download. jQuery also provides a non-minimized version that can be used for reading through the jQuery code or for debugging: "https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"

There are additional sources to link jQuery library as well (e.g by Microsoft). In fact, it is also possible to download the library file and then use the "src" attribute to link it to the local file system. However, the advantage of using a CDN is that since a lot of popular websites use the CDN version, it may have been already downloaded on the user's machine and so the page would not need to download it again. Please refer to jQuery's download page for additional details: http://docs.jquery.com/Downloading_jQuery .

In the above example, the second script tag is the one that actually holds the real jQuery code. We keep the jQuery code under the jQuery(document).ready() method. The ready() method in the $(document).ready() indicates that the page is ready for the jQuery script to be run. Without this event, it is possible that we can end up running the jQuery code even before the page is ready and that may lead to undefined behavior. Please note that the page being ready is different from page being loaded. The ready state happens sooner than the complete loading of the page.

In the above example, we end each line with a semicolon; this is a JavaScript property. In JavaScript, it is not required to end each line with a semicolon, but when we provide a semicolon, jQuery does interpret that as an end of statement. It is a good programming practice to use a semicolon at the end of each line to indicate that this is one line (statement) of code.

Lastly, the ready() function takes an anonymous JavaScript function. This is acceptable since in JavaScript, functions need not have a name and we can declare them and use them immediately. In fact, if we wanted, we could have given the function a name and then assigned that to the ready function. Here is a variant of the earlier program that does that.

 <!doctype html>
 <html>
 <!-- Let us start by including the jQuery library -->
 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
 </script>

 <body>
  <!-- Add a div element with CSS ID as "idDiv" -->
 <div id="idDiv"></div>

 <!-- Add a button with CSS ID as "idButton" -->
 <button id="idButton">Change my color!</button>

 <script type="text/javascript"> 
     // Callback function for the button click e vent.
     function funcCallback() {$("div").css("color", "blue");}

     // Define a separate function for the document ready event.
     function funcHelloAndChangeColor () {
         // Write something to the div element.
         $("#idDiv").append("Hello World!");

         // Call the funcCallback when button is clicked.
         $("#idButton").click(funcCallback);
     }

     // Setup the callback function for the document ready event.
     $(document).ready(funcHelloAndChangeColor);
 </script>
 </body>

 </html>

The above example shows the simplicity of jQuery() when it comes to selection of elements. Using the CSS id, all we have to do is $("#idDiv"). On the other hand, with JavaScript, we would need to use getElementById("idDiv") to get a handle of the element. Worse, there are some (older) versions of certain browsers that do not support getElementById(). With jQuery, we do not have to worry about these details. It is this simplicity and lucidity that has made jQuery popular.

Running the above example is very simple. Simply point the web browser to this location of the "jquery_hello.html" file. When we load the page, we would see the "Hello World!" text along with these button. When we click the "Change my color!" button, the "Hello World!" text would change to blue color.



Figure: jQuery "Hello World!" program

Separating jQuery and HTML

The popular way to add jQuery (or JavaScript) code to an HTML page is to add them to a separate JavaScript file (with extension as ".js") and then include the file in the main HTML page using the "src" attribute of the script tag.

This approach has two benefits. First, it separates presentation (HTML) from the jQuery logic. Due to this, the HTML page is cleaner to read/maintain and can continue to evolve without any dependency upon the jQuery logic. Thus, HTML file now becomes purely HTML and is not cluttered with jQuery script elements. Same goes for the jQuery file as well.

The second benefit is that if the jQuery include file is a common file, then it is likely that the first page would download it first and it would be still there in the cache for future pages. Without separating the two, we would end up downloading the same piece of jQuery script for all the pages that need to access it. Some what inefficient!

With that, let us rewrite our earlier program to separate the jQuery logic from the HTML page. The modified HTML page would now call another script tag to include the file, where we would store the jQuery logic. Here is the HTML file:

 <!doctype html>
 <html>
 <!-- Let us start by including the jQuery library -->
 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
 </script>

 <body>
  <!-- Add a div element with CSS ID as "idDiv" -->
 <div id="idDiv"></div>

 <!-- Add a button with CSS ID as "idButton" -->
 <button id="idButton">Change my color!</button>

 <!-- Next, let us include the jQuery application logic -->
 <script type="text/javascript" src="blue.js"></script>
 </body>

 </html>

For the included jQuery file ("blue.js"), we can merely move everything under the script tag into this file. Here is the file:

 // Filename: blue.js

 jQuery(document).ready(function() {
     // Write something to the div element.
     jQuery("#idDiv").append("Hello World!");

     // Set the event-handler for the click event.
     jQuery("#idButton").click(function() {
         $("div").css("color", "blue");
     });
 });

Whenever applicable, we would use examples where we separate the HTML code from jQuery logic.





comments powered by Disqus