jQuery Hello world example

JQuery is nothing but javascript which have very rich functionalities. It is faster and required less code. It has vast number of APIs that can perform DOM manipulation , CSS manipulation, Ajax, event handling.

Lets start with very simple  hello world example:

Download JQuery library

  • You can download .js library from jQuery website.
  • You can use direct CDN link(http://code.jquery.com/jquery-2.2.3.min.js) also in html file

Example :

Copy below text , open notepad , paste it and save it as jQueryExample.html and open it in the browser.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery</title>
<script src="http://code.jquery.com/jquery-2.2.3.min.js"></script>
<script>
  $(document).ready(function() {
    alert("Hello world !! document is ready");
}); 
  
</script>
</head>
<body>
</body>
</html>

Output:



Here $() indicates jQuery syntax and is used to define jQuery part. $(document).ready method get called when document is loaded.

Another Example : 

Lets use jQuery selector to change text of div.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery</title>
<script src="http://code.jquery.com/jquery-2.2.3.min.js"></script>
<script>
  $(document).ready(function() {
  $("#myButton").click(function() { $("#helloWorldDiv").html("jQuery Hello world example"); 
  });

});  
</script>
</head>
<body>    
<button id="myButton">Print Hello World</button>
</br>
</br>
<div id="helloWorldDiv"></div> 
</body>
</html>
Live Demo:
JQuery hello world example

Explanation:

We have used jQuery selector here. $(#id) actually selects DOM element with that id, so $(#myButton) selects button and when we click on that button,click function will get called.

then we are changing innerHTML of div with id "helloWorldDiv" with just
$("#helloWorldDiv").html("jQuery Hello world example");

If you use plain java scripts here, you have to do this

document.getElementById("helloWorldDiv").innerHTML = "Hello, world!";

We will learn more about jQuery selectors in next tutorials.





Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012