Follow this blog

Tuesday, March 10, 2009

jQuery hello world

This text contain brief tutorial how to use jQuery on your web and have one demo and one short and simple example.

First let's see what is jQuery?
jQuery is a lightweight JavaScript library that emphasizes interaction between JavaScript and HTML. jQuery is designed to change the way that you write Javascript.

To use jQuery you must have access to jQuery library. You can find jQuery library on http://jquery.com/. Choose production and download file.

jQuery download

To use jQuery you need to reference it on your page.

Example:

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

There is jquery-1.3.2.min.js file but the next version will have different name (probably jquery-1.3.3.min.js) so you will must change name of the file when there will be newer version. This work when you have Jquery library in same directory as your html page.

Another option is to reference jQuery library directly from google code.

Example:

<script src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js" type="text/javascript"></script>

Demo of disappearing paragraph with jQuery:


Example of Jquery, click paragraph
and it will fade away.



Code for disappearing paragraph with jQuery:


<html>
<head>
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script>
(function(){
$("#paragraph1").click(function () {
$("#paragraph1").fadeOut("slow");
});

});
</script>
<style>
#paragraph1 { font-size:150%; cursor:pointer; }
</style>
</head>
<body>
<p id="paragraph1">
Example of Jquery, click paragraph
and it will fade away.
</p>
</body>
</html>


We have reference to jQuery library (see above for explanation)

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


There is paragraph with id paragraph1

<p id="paragraph1">
Example of Jquery, click paragraph
and it will fade away.
</p>



With this we determine style for element with id paragraph1.
<style>
#paragraph1 { font-size:150%; cursor:pointer; }
</style>



This code says :
when paragraph1 is clicked ( $("#paragraph1").click(function ())
then fadeOut method is called with parameter slow ($("#paragraph1").fadeOut("slow");).

<script>
(function(){
$("#paragraph1").click(function () {
$("#paragraph1").fadeOut("slow");
});
});
</script>


In the end paragraph disappear after user click on it. Instead parameter slow can stand normal or fast. Or time in miliseconds.

Related articles:
jQuery on blogspot (blogger) post
jQuery selectors samples
Basic web effect with jQuery

No comments: