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 :


<!DOCTYPE html>
p { background:#DAA520; font-weight:bold; cursor:pointer; 
p.over { background: #ADFF2F; }
span { color:red; }
  <script src="jquery-1.4.2.js"></script>
	<p>Click or double click here.</p>
$("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){


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.

Share on Google+Share on Google+

Binding and unbinding events

Posted on: April 18, 2011 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: Binding and unbinding events  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
February 23, 2012

Looks nice but rolilng your mouse over it quickly keeps it animating even when the mouse isn't over the elements.Quick way to fix this (I'm sure you know) is to create timers on the roll over and kill them on mouse out. This method is used on a bunch of JS libraries to stop the constant jumping around when moving your mouse a lot.Pop it in a jquery plugin too