jQuery is a JavaScript library designed to simplify client-side scripting. jQuery enables the writing of cross-browser-compatible JavaScript code. Without it, it is tedious to write cross-browser-compatible code with JavaScript.
In this article, we will look at our “Hello, World!” program using jQuery.
We can download the 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 the jQuery library from CDNs:
<script src="https://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
Once we included the jQuery library in our files; it enables us to select HTML elements and perform the required actions on them. jQuery supports events to enable event-driven programming.
Let’s 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 accessed through the 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 the web browser.
Let’s check the below code: save this code as “hello.html”.
<html> <head> <script src="https://code.jquery.com/jquery-latest.min.js" type="text/javascript"> </script> <script> jQuery(document).ready(function(){ alert('Hello, World!'); }); </script> </head> <body> </body> </html>
In our code, we have selected a document with jQuery(document) code. As we discussed earlier, Document has a ready event. We need to pass an event handler to the ready event. So, this event handler will call when the event is raised.
We have created an anonymous function (without a name) and passed it to the ready event. Observe that we are passing the whole function body. And we placed an alert statement in the function body; an alert statement is used to display any message in the message box.
So, when the ready event is raised, our anonymous function gets called and the alert function will display the “Hello, World” message in the message box.
Once you saved the above code into the “hello.html” file; open the file in the web browser. You will see the “Hello, World!” message, once the page is loaded.
.Paul.