Binding and unbinding events

Ads
 

Binding and unbinding events

This page discusses - Binding and unbinding events

This page discusses - Binding and unbinding events

Binding and unbinding events

     

Binding and unbinding events

As the name says "binding events " is  the association of an element with an event. And reverse is true for "unbinding events" That is disassociation of an element with an event.

Binding events

You can bind events like click, mouseenter, mouseleave etc events with any elements like paragraph, div, span ,button etc.

Given below example demonstrate how to bind event with element :

bindEvent.html

<!DOCTYPE html>
<html>
<head>
  <style>
p { background:#DAA520; font-weight:bold; cursor:pointer; 
padding:5px;width:20%;}
p.over { background: #ADFF2F; }
span { color:red; }
</style>
  <script src="jquery-1.4.2.js"></script>
</head>
<body>
	<p>Click or double click here.</p>
<span></span>
<script>
$("p").bind("click", function(event){
var str = "( " + event.pageX + ", " + event.pageY + " )";
$("span").text("Click happened! " + str);
});
$("p").bind("dblclick", function(){
$("span").text("Double-click happened in " + this.nodeName);
});
$("p").bind("mouseenter mouseleave", function(event){
$(this).toggleClass("over");
});

</script>
</body>
</html>

Output  :

When we click one time :

 When we click two times :

 Description of the program :


1 $("p").bind("click", function(event){
2 var str = "( " + event.pageX + ", " + event.pageY + " )";
3 $("span").text("Click happened! " + str);});
4 $("p").bind("dblclick", function(){
5 $("span").text("Double-click happened in " + this.nodeName);});
6 $("p").bind("mouseenter mouseleave", function(event){
7 $(this).toggleClass("over");});

At first line , paragraph 'p' is associated with click event means when paragraph is clicked , it will execute lines 2 & 3.

Similarly the double click is associated  at line 4,  which executes line 5.

And at last, 'p' binds with "mouseenter mouseleave"  event, which changes the color of the 'p' by executing line number 7.

Download Source Code

Click here to see online demo

Learn from experts! Attend jQuery Training classes.

Ads

Ads