In this article we will look at our “Hello, World!” program using jQuery.
We can download jQuery library from jQuery.com. Instead of downloading it, we can include the library from several Content Delivery Networks; such as Google, Microsoft, etc., To include the jQuery library from Content Delivery Networks (CDNs), we use script tags. Below is the way how we can include jQuery library from CDNs:
Once we included the jQuery library into our files; it enables to select HTML elements and perform required actions on them. jQuery supports events to enable even driven programming.
Lets check a Document‘s event, ready; and we will use this event in our “Hello, World!” program.
- We know that, each HTML page is represented as a Document object.
- All HTML elements mentioned in the HTML page can be accessible through Document object.
- When the HTML page is loaded, the web-browser will raise an event to inform whether the HTML page load is completed or not.
- We can catch this event using jQuery and display our message “Hello, World!” within the event handler. It means, our message will be displayed when the page is loaded into web-browser.
Lets check the below code: save this code as “hello.html”.
In our code, we have selected document with jQuery(document) code. As we discussed earlier, Document has ready event. We need to pass an event handler to ready event. So, this event handler will call when the event raised.
We have created an anonymous function (without name), and pass it to the ready event. Observe that we are passing whole function body. And we placed alert statement in the function body; alert statement is used to display any message in message box.
So, when ready event is raised, our anonymous function gets called and the alert function will display “Hello, World” message in message box.
One you saved the above code into “hello.html” file; open the file in web-browser. You will see “Hello, World!” message, once the page is loaded.