 |
Welcome to Databloc's introduction to the jQuery library, a basic guide to getting started. Please note, it is recommended that you have basic knowledge of javascript and the Document Object Model (DOM).
An Overview
jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript which is currently compatible with IE 6.0+, FF 2+, Safari 2.0+, Opera 9.0+.
An Example
Firstly, you must download and include the library into your web page. You can get a copy from jQuery.com or Google Code. Once you have a copy add it into your web page like so.
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
// Your code goes here
</script>
</head>
<body>
<a href="http://www.jquery.com/">jQuery!</a>
</body>
</html>
The above code creates a standard HTML page with the jQuery library.
The first thing to do whenever we use jQuery to manipulate the document object model (DOM), we need to make sure that it is ready. To do this, we register a ready event for the document.
$(document).ready(function() {
// do stuff when DOM is ready
});
Putting an alert into that function does not make much sense, as an alert does not require the DOM to be loaded. So lets try something a little more sophisticated: Show an alert when clicking the link.
$(document).ready(function() {
$("a").click(function() {
alert("Hello world!");
});
});
Lets have a look at what we are doing: $("a") is a jQuery selector, in this case, it selects all a elements. $ itself is an alias for the jQuery "class", therefore $() constructs a new jQuery object. The click() function we call next is a method of the jQuery object. It binds a click event to all selected elements (in this case, a single anchor element) and executes the provided function when the event occurs.
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("a").click(function() {
alert("Hello world!");
});
});
</script>
</head>
<body>
<a href="http://www.jquery.com/">jQuery!</a>
</body>
</html>
|
 |