Search This Blog

Loading...

Wednesday, August 14, 2013

Why not jQuery? it is Fast, powerful, cross browsers and easy to use framework.

jQuery, jQuery then jQuery, yeah it simplifies the way you touch the HTML via JavaScript.

On jQuery site, its definition as the following:
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.
Yes, I agree totally with this statement, I make use of the JavaScript framework, jQuery. jQuery simplifies common tasks and provides a single interface to actions that are implemented inconsistently in different browsers. Perhaps the most common use of jQuery in my development is reading in files (XML, JSON, text …etc) or other data from web services, but it also make it easy for traversing the DOM and applying CCS to components in easy way.

The following section is meant to give a quick introduction to using jQuery, and making your hands dirty with code to get the idea. For advanced features of the framework, you can branch to jQuery documentation and API references.

But, wait here for a second, be patient, before you can use jQuery, you need to include it in your web page. You can do so by downloading the latest version at http://jquery.com/ or by grabbing a Google-hosted version by adding the following to the <head> section of your HTML file:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
As of time of this writing, the latest version of jQuery is 2.0.3, and also there are Other CDNs could be used, and are listed on jQuery home page, I have used here Google one.

After adding the library to your page lets, get in touch with jQuery functionality and development.

Once you have included jQuery in your document, you can use its functions via two global variables: jQuery and its shorthand, $.

Demo page structure:
We will use this page in our journey, for the sake of clarity of how to use jQuery.
<head>

jQuery Example
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<style>
.content
{
 padding: 20px;
 width: 200px;
 height: 200px;
 background-color: #CCC;
}

#eventInfo
{
 width: 420px;
 height: 20px;
 background-color: #000;
 color: #CCC;
 font-weight: bold;
 margin-top: 10px;
}
</style>

</head>
<body>
</body>
Query Document Objects
Among its many uses, jQuery is very helpful at quickly and easily extracting elements from your HTML page into JavaScript code. You can query by id, tag name, CSS class, or combinations of these factors. jQuery makes this task easier, so you can focus on what you want to do with those elements.

To grab a single piece of the page, such as the content <div>, you call it by its id. Much of jQuery’s syntax is borrowed from CSS, which may look familiar.

Here is how you would call an object with an id of content:
Notice:
I am using the dollar-sign shorthand. Then I add parentheses because $ is a variable and a function (jQuery stretches the bounds of JavaScript in ways that you and I probably will not). Inside the function, we pass a string with the CSS we would use to style the map div, #content.

Let us see how to add a text to this div content, just use one of the following snippets of code:
Or simple chaining one
You have now used your first jQuery function to query for a specific element and add a text to it. You can achieve the same result with JavaScript’s standard document.getElementById function, but jQuery’s method is faster to type. Plus, the result using $ allows you to chain other jQuery functions, such as visual effects, binding events or applying values and css as we have made in the previous code.

Notice:
Every jQuery function returns a jQuery object wrapping the queried element(s). Therefore, we can use the functions call-chaining mechanism, this pattern is called builder design pattern.

jQuery can also do more than just query individual elements; it can gather multiple elements in a single call. Here are a few examples:
Each of these examples shows a different type of querying—and many more are possible. You can learn about what jQuery calls selectors at http://api.jquery.com/category/selectors/.

Use jQuery to fire browser events
jQuery provides a lean way to use and fires browser events, such as clicking, double clicking or dragging. You can also react to events anywhere in the browser, and jQuery makes reacting a simple process for us.

To respond to an event, you first need to be listening for it. To do so when your page first loads, you register your intention to react to an event. You can do this by adding a JavaScript function to the onload attribute of your <body> tag. Or you can do this with a special jQuery ready event.

Although creating an event to register other events may seem counterintuitive, but believe me it works. Here is an example that waits until the page is ready:
Notice:
That the element we are querying for is a little different from in the past. Instead of a string inside the parentheses, we have inserted a standard JavaScript object, document. When enough of the page has loaded that the browser knows all the objects it contains, we call the register_events function.

That register_events function does not exist, however, so we need to write it. Or, instead, we could react to the same event with an anonymous function:
As with most anonymous functions, you usually want to keep it to just a few lines. If you have many events to register, you are probably best served with a named function.

Note
A big difference exists between using your browser’s onload attribute and jQuery’s ready event. With onload, you wait until the entire page is loaded, including images and other external files. With $(document).ready, you can run code, such as registering events and hiding objects, the moment the browser is ready. Using jQuery here often translates to a better user experience.
Now that you have waited for the browser to be ready to register other events, let us register them. Here is the basic pattern for jQuery events:
The element portion is usually a selector, such as an element’s id (though it can also be any browser object, as shown in the ready example). The event piece is the name of the function, as declared by jQuery. Finally, function is the function reference, either an anonymous function or the name of the function to call.

Here is how you would listen for a particular element to be double clicked:
If you are familiar with JavaScript events included in HTML, you might be wondering where the on, as in onDblClick, went. In jQuery, events are referenced with only the action so it is dblclick.

You can also get additional information about the event. The information available may be a little different depending on the event. Here is how you find out where the user has double-clicked on a page:
I used a dblclick event. Because we want more information about the event, I included an optional parameter e to the anonymous function. Within the function, I can use that variable to get information, such as where the user double clicked. This data comes in two pieces:

The number of pixels from the left side of the page X and the number from the top of the page Y. You can see a sampling of available events in Table 1, along with the additional information that is passed in the optional parameter to each event.

Tip: Try also to double click inside content1 div, at different location and watch how X and Y
value changes.
Table 1: Some Useful jQuery Events

Event Name

Objects Available

Additional Information

click

Any


Page location: pageX, pageY

dblclick

Any

Page location: pageX, pageY

mousemove

Any

Page location: pageX, pageY

keydown

document, window

Key code

focus

Form elements

 
Events will make your web pages much more interactive. For a full list of events (and additional event information available), see jQuery’s documentation at http://api.jquery.com/category/events/.

Insert and Hide Content

Once you have one or more elements from the page using jQuery, you need to do something to them. Here, I will show you a way to add or replace the content inside a page element. In addition, I will also demonstrate an effect that will hide the content, so later, you can make it reappear.

Let us say you want an element on your page where you can show the event information raised from previous double click event such as event type and the event source id. You can add the element with HTML using something like this:
When you are ready to add the event information, you can use jQuery to find the element and then display the event information. If you want to display the content of a variable called info, you could use this single line of jQuery:
This line will find the element on the page with the id of eventInfo and then replace its inner HTML with the value in the info variable. If you just want to add additional content to the element, use this line instead:
Alternatively, use can use chaining feature as the following.
Now the eventInfo div content will look something like this:

Event Info: Event type is: dblclick, raised from: content1

You have seen how to insert content, but what about making that same content disappear? For example, before adding the event Information, a page with just Results: without anything after it looks a bit funny. So when the page loads, run the following code to hide the results element:
Moreover, when you are ready to display the results to the user, include this code:
On the other hand, append it to the last of your chaining command as the following:
These two functions are simple (and very useful) examples of jQuery effects. Many more effects are listed on the jQuery website at http://api.jquery.com/category/effects/.

Final code


jQuery Example
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<style>
.content
{
 padding: 20px;
 width: 200px;
 height: 200px;
 background-color: #CCC;
}

#eventInfo
{
 width: 420px;
 height: 20px;
 background-color: #000;
 color: #CCC;
 font-weight: bold;
 margin-top: 10px;
}
</style>
<script type="text/javascript" language="javascript">
   //Use ready function to execute all code after browser parse and build DOM tree.
   $(document).ready(function(e) {
     
  // Hideing div with id eventInfo
  $('#eventInfo').hide(); 
  
  // Setting dive text and applying css value for the text to be of color red
  $('#content').text('My name is Mohamed Taman').css('color','red').append('

');
  
   //Get the first span wrapped inside the div with css class 'content' and set its text 
  $('.content span:first').text('Number of divs in the document are: ' + $('div').length);
  
  
  // Register div with id content1 to double click event
  $('#content1').dblclick(function(e) {
        alert('I am double clicked with and event location at, X: '+ e.pageX +', and Y: '+ e.pageY);
 
  var info = 'Event type is: '+ e.type +', raised from: '+ e.target.id;

  $('#eventInfo').html('Event Info: ').append(info).show();
    });
});
</script>

<body>
</body>
Let's wrap up

By now, we have reached to the end of the article, and I hope you enjoyed and find it useful.

In the next part, I will demonstrate an important issue, which is loading and reading data files using jQuery either it is JSON or XML data files. So If you want to interact with data outside of your current HTML file, jQuery has some excellent tools for doing these sorts of Ajax calls. Though Ajax is short for Asynchronous JavaScript And XML, you can access any type of data with Ajax.