Monday, April 1, 2013

Introduction to JQuery

We know that JQuery is a javascript library. So, as a first step you need to import its library in order to use its functions, methods and events. You can do this in two ways either download the jQuery library from JQuery.com or include it from a CDN.

CDN stands for Content Delivery Network or Content Distribution Network. It is responsible for delivery or distribution of your content to your visitor’s server. It consists of servers all around the world. When you integrate with CDN, your content gets copied on all its servers. So, when a visitor tries to access your blog or website, content is delivered to him each time from the nearest server geographically instead of your hosting server.

 Once you have downloaded it, now include it into your project by simply including following lines:

<head>
<script src="jquery-1.9.1.min.js"></script>
</head>

Note that you have to import this file using <script> tag under <head> section.

And if you want to include it from a CDN, use one of the following codes:
  • <head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
    </script>
    </head> 
  • <head>
    <script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js">
    </script>
    </head>
Now once you have included its javascript file now you can start using jquery in your code and see results.  

jQuery library contains many features like HTML/DOM manipulation, CSS manipulation,  HTML event methods, effects and animation, Ajax and plug ins for almost any task.

We use $ sign to define or access jQuery. Syntax for using jQuery to access or manipulate any object is:

Syntax: $(selector).action()

For example: To hide all <p> elements on a page we can use: $("p).hide();

And if we want to hide selected <p> elements, that is, when we click any <p> element then only that should hide than:


$("p").click(function(){
$(this).hide();
}

Remember we put all the jQuery code in a special event that is $(document).ready(function()). This is a document ready event. It is a good practice to write the entire jQuery code in this block as it prevents any jQuery code to execute before or while the page is loading. So, the above code goes as:

<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("p").click(function(){
    $(this).hide();
  });
});
</script>
</head>


In our next discussion we will check different selectors and events.

No comments:

Post a Comment