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
snippet
<!DOCTYPE html>
<html>
<head>
 <title>First jQuery Example</title>
 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
 </script>
 <script type="text/javascript" language="javascript">
 $(document).ready(function() {
 $("p").css("background-color", "cyan");
 });
 </script>
 </head>
<body>
<p>The first paragraph is selected.</p>
<p>The second paragraph is selected.</p>
<p>The third paragraph is selected.</p>
</body>
</html>

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.

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

The above code is equivalent to this code.

snippet
$(function() {
 $("p").css("color", "red");
 });

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

File: shortjquery.html
snippet
<!DOCTYPE html>
<html>
<head>
 <title>Second jQuery Example</title>
 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
 </script>
 <script type="text/javascript" language="javascript">
 $(function() {
 $("p").css("color", "red");
 });
 </script>
 </head>
<body>
<p>The first paragraph is selected.</p>
<p>The second paragraph is selected.</p>
<p>The third paragraph is selected.</p>
</body>
</html>

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.

Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents