Oct 31, 2008

Intro to JQuery

JQuery is a lightweight JavaScript framework that got a lot of attention lately so I decided to write few rows about it.

This post-tutorial is recommended for people with basic javascript, html and css knowledge.

To run and test the examples in this tutorial, you need to save them as html pages. You can use any text editor like notepad or anything convenient.

What do you need to start using JQuery? Just download and save it in the same directory (I’ll call it jquery.js) and include the following code anywhere above your javascript code:


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



The best place for our javascript code is in the head section of the html document but you are not restricted to it. Anyway I’ll use the head section for most of my examples.

Ok, let’s use some basic functionality to test if we’ve done it right.

example1.html:

<html>
<head>
<title>JQuery basic tutorial</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
alert('Works!!!');
} );
</script>
</head>
<body>
JQuery basic tutorial
</body>
</html>




So, what happens here? Nothing special, we just show an alert with text ‘Works!!!’.

$ function is a factory method (shortcut) for the JQuery object.


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



With $(document).ready we register our code to the ready event of the document. The above code can be shortened:


$(function () {
// code
} );



Selectors and events



In JQuery an element can be selected in different ways – by id, by element type, by css class and so on.
This is a simple code showing how to use events and selectors:


<html>
<head>
<title>JQuery basic tutorial</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function () {
$("#ourID").click(function () {
alert("Click");
});
} );

</script>
</head>
<body>
<h1>JQuery basic tutorial</h1>
<div id="ourID" style="font-size: larger;background-color: #FFA500;border : medium dashed;text-align: center; width: 250px">
Div
</div>
</body>
</html>



The click(fn) binds a function to the click event of our matched element.
Let’s make our example a little more complex. We will count the clicks.


<html>
<head>
<title>JQuery basic tutorial</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var counter = 0;
$(function () {
$("#ourID").click(function () {
counter++;
$(this).html(counter);
});
} );

</script>
</head>
<body>
<h1>JQuery basic tutorial</h1>
Click in the box:
<div id="ourID" style="font-size: larger;background-color: #FFA500;border : medium dashed;text-align: center; width: 250px">
0
</div>
</body>
</html>


3 comments:

Dipin Krishna said...

Good Site..
Visit Linux Programming in C

Anonymous said...

Just the simple intro I was looking for. Thanks!

Anonymous said...

Just the simple intro I was looking for!

Popular Posts