Today we will look into jQuery Hello World program. In the earlier post, we discussed what is jQuery?. Here we will learn how to download and install it and then run a simple “jQuery Hello World” program.
Download jQuery
jQuery is a javascript library and comes in a single JS file, you can download it from jQuery Official Website. There are development and production versions, you can download any one of these to learn jQuery but in a production environment, you should use jQuery minified production version.
Installing jQuery
Once you have jQuery JS downloaded, you can use it in any HTML, JSP, PHP files by including it in the head section.
1 2 3 |
<script type="text/javascript" src="https://www.journaldev.com/887/jquery-3.2.1.min.js"></script> |
Note that the src path is relative here, in above case HTML and jQuery JS file should be in the same directory.
jQuery Hello World
Here is our first HTML with jQuery hello world functionality.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<html> <head> <title>My First jQuery Example</title> <script type="text/javascript" src="https://www.journaldev.com/887/jquery-3.2.1.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#msg").html("<h2>jQuery Hello World</h2>"); }); $(document).ready(function() { $("#newdiv").click(function() { alert("Hello world!"); }); }); </script> </head> <body> <p>This is Hello World by HTML</p> <div id="msg"> </div> <br/> <div id="newdiv"> Click on this to see a dialogue box. </div> </body> </html> |
When I open above HTML in a browser, here is what I get after clicking on the last line.
jQuery Functions Explanation
1 2 3 4 5 |
$(document).ready(function(){ $("#msg").html("<strong>Hello World by JQuery</strong>"); }); |
$() is the syntax for jQuery function, here when DOM elements are ready or fully loaded, an element with id “msg” HTML is set by this function. Here we are using jQuery for manipulating the HTML data.
1 2 3 4 5 6 7 |
$(document).ready(function() { $("#newdiv").click(function() { alert("Hello world!"); }); }); |
Here we are using the mouse click event to show the alert for all the elements with id “newdiv”. That’s all for getting started with jQuery and jQuery hello world program.