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