Thursday, November 12, 2009

Have fun with jQuery - Tutorial 1

jQuery is a simple javascript API which can be used in many ways to improve your web application or Web site.
First of all you have to download the jQuery javascript file from here (jquery-1.3.1.min.js). Then you can add it to your project like this way,

 <script type="text/javascript" src="jquery-1.3.1.min.js"></script>


Else you can use refer this link "http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" on development.
Then you will import js file this manner,
 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>



Now your are ready to start develop with jQuery.
Let's begin with a simple example.
Create a simple html file which is having a html component. You can use any component. In this case, Let's get a <a> tag. It can be a button, submit, label or any thing.


<html>
<head>

<script type="text/javascript" src="jquery.js"></script>

<script type="text/javascript">

</script>
</head>

<body>
<a href="http://www.google.com/">My test link</a>
</body>
</html>


We are going to use ready status of the page loading. Since that, we used to write as following simple code,

 $(document).ready(function(){
// Your code content here
});


Assume you want to give a pop up when you clicked on the "My test link". It is very simple.
 $(document).ready(function(){
$("a").click(function(event){
alert("We are going to visit google....!!!");
});
});


It will give you a popup and will direct to google.com.

Let's assume that you don't need to visit to google.com. Then there is a jQuery functionality for disable default functions of the element. What you have to do is add preventDefault() method to onclick function event. It can be achieved easily following way.

 $(document).ready(function(){
$("a").click(function(event){
alert("We are going to visit google....!!!");
event.preventDefault();
});
});



Now you will receive the popup, but you will not forward to google.com.
According to above code, it will be applied for all places where <a> tags are available. It is possible to write this kind of event handling and many more things using jQuery. Let's meet on next tutorial to see how the things can be applied for specified (specified by the id) elements.
Thank you.
See you soon...

No comments:

Post a Comment