Monday, December 19, 2011

Hello jQuery / Getting Started with jQuery

We start with an empty html page or .aspx page.This page just loads the .js library (make sure the URL points to where you stored your copy of jquery).As almost everything we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events as soon as the DOM is ready.
To do this, we register $(document).ready event for the document. 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 a link.

Here is script.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
//otherwise, you can use built-in .js file while you use VS 2010.
<script type="text/javascript">
 $(document).ready(function() {
   $("a").click(function() {
     alert("Hello world!");
   });
 });
</script>

//Add the following to the <body>:
<a href="">Link</a>

This should show the alert as soon as you click on the link. Let's 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.

This is similar to the following code:
<a href="" onclick="alert('Hello world')">Link</a>

The difference is quite obvious: We don't need to write an onclick for every single element. We have a clean separation of structure (HTML) and behavior (JS), just as we separate structure and presentation by using CSS.

Source : http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery#Hello_jQuery

No comments:

Post a Comment