Hello jQuery

If you are developing JavaScript's for a web application that should run in the wild, you know the pain of writing code that should run on large part of the available browsers. A common approach is delegating to a library the bore of taking care of the details, better if it has the side effect of providing a high level interface. A popular choice in this field is represented by jQuery, recently released in its 1.8 version.

Writing an Hello jQuery application is pretty easy.

Firstly, you'd better get the library on your local machine. You can fetch it following the instructions in Download jQuery.

Actually you could avoid this step and refer to a publicly available copy of it, see CDN hosted jQuery for details. Whichever strategy you follow, you should ensure your script gets access to the jQuery library. In my case, I have simply put the js file in the same directory of the html that you can see below.

My hello page pops up an alert with greetings after the HTML page is fully loaded. It is not much, but this ensures that the jQuery library is properly linked:
<html>
<head>
    <meta charset="UTF-8">
    <title>Hello jQuery</title>
    <script src="jquery-1.8.0.js"></script> <!-- 1 -->
    <script>
        $(function(){ // 2
            alert("Hello from jQuery");
        });
    </script>
</head>
    <body>
        <h1>A JavaScript/jQuery powered page</h1>
    </body>
</html>
1. I ask to the browser to go and load the jQuery library. I have put it in the current folder, so I specify just its name. In production code, it would almost certainly be somewhere else.
2. I called a function named $ (just the single character "dollar"), passing to it an anonymous function that calls the alert() function. This is quite an implicit way of calling the jQuery ready event handler. Maybe it looks more clear if I rewrite it in this way:
jQuery(document).ready(function() {
    alert("Hello from jQuery");
});
The dollar sign is a mere synonym for the jQuery() function. And, if you dig in the jquery.js code, you'll find out that passing a function to jQuery is a shortcut for calling the document ready event handler.

Putting our call to alert() in the jQuery ready() body, we ensure that it is called only after the DOM document associated to the current HTML page is fully loaded.

No comments:

Post a Comment