jQuery Example

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

jQuery Example

jQuery is developed by Google. To create the first jQuery example, you need to use JavaScript file for jQuery. You can download the jQuery file from jquery.com or use the absolute URL of jQuery file.

In this jQuery example, we are using the absolute URL of jQuery file. The jQuery example is written inside the script tag.

Let's see a simple example of jQuery.

File: firstjquery.html

 
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.  <title>First jQuery Example</title>  
  5.  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">  
  6.  </script>  
  7.  <script type="text/javascript" language="javascript">  
  8.  $(document).ready(function() {  
  9.  $("p").css("background-color", "cyan");  
  10.  });  
  11.  </script>  
  12.  </head>  
  13. <body>  
  14. <p>The first paragraph is selected.</p>  
  15. <p>The second paragraph is selected.</p>  
  16. <p>The third paragraph is selected.</p>  
  17. </body>  
  18. </html>  

Test it Now

Output:

The first paragraph is selected.

The second paragraph is selected.

The third paragraph is selected.

$(document).ready() and $()

The code inserted between $(document).ready() is executed only once when page is ready for JavaScript code to execute.

In place of $(document).ready(), you can use shorthand notation $() only.

  1. $(document).ready(function() {  
  2. $("p").css("color", "red");  
  3. });  

The above code is equivalent to this code.

 
  1. $(function() {  
  2. $("p").css("color", "red");  
  3. });  

Let's see the full example of jQuery using shorthand notation $().

File: shortjquery.html

 
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.  <title>Second jQuery Example</title>  
  5.  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">  
  6.  </script>  
  7.  <script type="text/javascript" language="javascript">  
  8.  $(function() {  
  9.  $("p").css("color", "red");  
  10.  });  
  11.  </script>  
  12.  </head>  
  13. <body>  
  14. <p>The first paragraph is selected.</p>  
  15. <p>The second paragraph is selected.</p>  
  16. <p>The third paragraph is selected.</p>  
  17. </body>  
  18. </html>  

Test it Now

Output:

The first paragraph is selected.

The second paragraph is selected.

The third paragraph is selected.


function() { $("p").css("background-color", "cyan"); }

It changes the background-color of all <p> tag or paragraph to cyan.