jQuery Basics

In this tutorial we will cover the basics of jQuery. This is the second tutorial on jQuery. Before reading on it is recommended that you go through the first tutorial - jQuery Introduction.

jQuery follows a typical format or syntax. No matter which type of task we have to to do in jQuery, we always start with a dollar sign and parentheses: $(). Inside parenthesis we define what type of HTML element we want to select on which some action has to be performed - $('selector'). This is followed by some action which has to be performed on the HTML element selected. So the complete syntax is - 

$('selector').action();

Let's illustrate this with an example -

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("p").click(function(){
    alert("The HTML element <p> has been selected and this alert box is triggered when you click(action) on it");
  });
});
</script>
</head>

<body>
<h2>jQuery Syntax Example</h2>
<p>Try clicking on me and see what happens</p>
<p>Click me too.</p>
</body>
</html>  

 

Try out this example in our Online HTML Compiler and you will see that when you click on a paragraph an alert box is displayed. Try clicking on the second para and you will still get the same alert box. Lets analyze the part of the jQuery code displayed in bold below.

$(document).ready(function(){
  $("p").click(function(){
    alert("The HTML element <p> has been selected and this alert box is triggered when you click(action) on it");
  });

});

 

Here our selector is <p> tag - $.("p") and action is click(). And we have given a function as the parameter of click() which executes the alert() function in return and finally displays the message. More on this will be discussed in further tutorials of jQuery.

You must have seen in the above example as well as in the example given in the first tutorial that we write the jQuery code inside the $(document).ready().

$(document).ready( function() {

//Your code here

});

 

This causes our code to run after the page is completely loaded. If we try to run jQuery code directly it may fail because it might be possible that jQuery is trying to perform an action on some Html DOM element which hasn't loaded yet. In this case our action will fail. So it is necessary to include your code inside the $(document).ready().