AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=1736&pId=-1
Introducing jQuery
page
by Debjani Mallick
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 21357/ 40

Introduction

jQuery is a JavaScript library developed by John Resig. It basically simplifies JavaScript and AJAX programming. We must be familiar about what JavaScript is and how it is used. In one line, JavaScript is a cross-platform, object-based scripting language developed by Netscape. It is used to add interactivity and dynamic content to web pages. And AJAX is the short form of Asynchronous JavaScript and XML. It is basically a technique used for handling external data asynchronously through JavaScript, without the requirement of reloading an entire page. jQuery emphasizes the interaction between JavaScript and HTML.

Basics of jQuery

jQuery contains all the common DOM, event, effects, and Ajax functions in a single JavaScript file. Unlike other libraries which normally operate by introducing new classes and extending the built-in JavaScript classes, jQuery, rather than extending classes, provides a new class called jQuery. It acts as a wrapper around objects for providing extended operations upon those objects. For making use of jQuery, the particular JavaScript file (i.e. the jQuery file) needs to be included in the file which is going to use the jQuery functionality.

Advantages

The benefits of using jQuery are:

It helps in enhancing JavaScript without adding a lot of burden to learn some new syntax or way of coding. It basically uses the knowledge what one already has on JavaScript.

jQuery helps in keeping the code simple, clear, readable and reusable.

It is no longer required to write a bunch of repetitious and tedious loops and DOM scripting library calls. Using jQuery, it is possible to get right to the point and act on it using the fewest possible lines of code.

jQuery's chainable methods allow a programmer to write much more compact code than other JavaScript libraries.

Getting Started

Let us start first with the design of the HTML page where we are going to use jQuery functionality.

Listing 1

<html>
  <head>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
      // jQuery code goes here
    </script>
  </head>
  <body>
      <--- HTML content should go here --->  
  </body>
</html>

As you can see, we have included the jquery.js file in the first line. Here it has been assumed that the JavaScript file is present in the same folder where the HTML file resides. If it is not in the same folder, we need to pass the path to the JavaScript file in the "src" attribute of the script tag.

Now let us add some content to it – a link using the <a> tag.

Listing 2

<a href="http://www.aspalliance.com">ASPAlliance Site</a>

It should be remembered that almost everything that we do while using jQuery, reads or manipulates the Document Object Model (DOM). So we need to make sure that we start adding events as soon as the document gets ready. To do that, we need to register an event – the ready event.

Listing 3

$(document).ready(function() {
  // action to be performed when DOM gets ready
});

The ready event forms the basic of jQuery. The logic used by jQuery is very simple: find things and act on it. $() is a jQuery function that is used to select elements from the document through DOM. It is equivalent to document.getElementById() function in JavaScript with the exception that along with supporting IDs, it also supports CSS and some XPath selectors. For example:

Listing 4

$("#id of an element")

The above statement will wrap the element having the above provided ID for manipulation. Similarly, the statement below will wrap all elements, regardless of type, that possess the class provided below, for manipulation.

Listing 5

$(".class name")

Another difference is that jQuery can return an array of elements, instead of one element. After making the selection or in other words, after finding the required element, we can use functions to perform actions on our selections.

Now, let us add something in between the lines to happen on the click event of the above link.

Listing 6

$(document).ready(function() {
   $("a").click(function() {
     alert("You have clicked on the link!");
   });
});

On clicking the link to the ASPAlliance site, we would get an alert message and then on clicking ok, we would be redirected to the ASPAlliance site. Now, what we are doing above is the - $("a") selector selects all anchor elements in this case. $() constructs a new jQuery object and the click() function called next is a method of the jQuery object. It binds a click event to all selected elements, which in this case is a single anchor element, and executes the written function when the event occurs.

The same action can be performed by the JavaScript code.

Listing 7

<a href="http://www.aspalliance.com" 
  onclick="alert('You have clicked on the link!')">ASPAlliance Site</a>

The difference is that it is not required to write an onclick for every single element. Another advantage is that we have a clean separation between the structure (the HTML) and the behavior (JS), just as we separate structure and presentation by using CSS. 

Normally, while developing web pages, we use some initialization code to execute so that we have our page ready before the user starts interacting with the page. For this we rely on window.onload functionality which guarantees the page to be loaded prior to executing the onload code, so that DOM elements exist and are ready for manipulation. But the problem is that it not only waits for the document body to be loaded, but also for all the images to be loaded. But since the images are fetched from the server, if the browser does not cache them, this can extend to a point at which the initialization code runs far beyond the point at which the document has been loaded and the code is safe to execute. jQuery solves the problem by introducing the concept of document ready handler which we have used above. This mechanism makes a function to execute when a document has loaded, but prior to waiting for any images and the onload event handler.

What we have done above is very simple. Let us try doing something that is not obvious – like preventing the link from going to the URL pointed by the href attribute of anchor tag. This can be done by simply modifying the above code a little bit.

Listing 8

$("a").click(function(event){
  event.preventDefault();
  alert("Prevented to go to the link”);
});

Isn't it cool!

Adding a class

It is one of the common tasks that a developer performs on a web page - adding and removing classes. For adding a class, we have to use addClass() function.

Listing 9

$("a").addClass("tableStyle");

It has been assumed that tableStyle is a predefined class. Similarly for removing a class, we can use removeClass () function.

Chainability

jQuery allows us to concatenate together operations into a single expression. Every method within jQuery returns the query object itself, allowing the programmer to "chain" upon it. In other words, most of the jQuery wrapper methods returns a reference to the jQuery object itself so that we can go on adding operations to a single expression when we need to perform multiple manipulations on the wrapped object. Let us take the example of the statements below.

Listing 10

$('#someId').addclass('someClass');
$('#someId').show();

The operation performed by the above two statements can be performed in one statement as shown below.

Listing 11

$('#someId').addclass('someClass').show();

Like the above examples, there are a lot of functionalities which can be performed using jQuery using the minimal code.

Conclusion

I hope after reading the article, you have gained a good knowledge about jQuery.

By Debjani Mallick


Product Spotlight
Product Spotlight 

©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-26 8:41:36 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search