Understanding the jQuery event handling mechanism

This page discusses - Understanding the jQuery event handling mechanism

Understanding the jQuery event handling mechanism

Understanding the jQuery event handling mechanism

     

Understanding the jQuery event handling mechanism

First of all , you need to know -What is an event ?

An event is an action or occurrence detected by a program. It may be mouse click, keyboard button press, mouse pointer hover etc.

In jQuery for handling events , it provides many efficient method to handle these event. Event handling methods basically associates an event with  an function . For example on button click , the paragraph will disappear.

Let us take this example in detail. Consider the given code :

jqHideParaOnClick.html

<!DOCTYPE html>
<html>
<head>
<style>
p { background:#DAA520; font-weight:bold;}
</style>
<script src="jquery-1.4.2.js" type="text/javascript"></script>
</head>
<body>
<button id="butt1">Click to hide Paragraph</button>
<button id="butt2">Click to show Paragraph</button>
<p>This will Hide after clicking button</p>
<p>It will hide too....................</p>
<script>
$("#butt2").hide();
$("#butt1").click(function () {
$("p").hide("slow");
$("#butt1").hide("slow");
$("#butt2").show("slow");
});
$("#butt2").click(function () {
$("p").show("slow");
});
</script>
</body>
</html>

It will produce following output :

When you click on button the paragraph will disappear :

When you click on it , it will again display paragraph :

Description of the program :

Observe the script carefully. You can notice that firstly the button2 is set to invisible mode by :

$("#butt2").hide();

After it the following script is set for click event of button1 :

$("#butt1").click(function () {
$("p").hide("slow");
$("#butt1").hide("slow");
$("#butt2").show("slow");
}); 

Here ,at first line ,you can see that button1 is associated with click event. When this event is triggered on this button, the code lines which follow him will execute.

The inside code lines are used to hide paragraph ,hide button1 , show hidden button 2 .

One thing to note here that hide or show have a "slow " attribute , it means the appearance or disappearance will take effect slowly.

Download Source Code

Click here to see online Demo

Learn from experts! Attend jQuery Training classes.