jQuery Event Handling: Binding and Unbinding


Video tutorial to demonstrate binding and unbinding of events in jQuery.

Events are objects which has data and methods in it.

In this tutorial we are taking 3 paragraph tags with some text inside it.
Once the user clicks on a paragraph, we display the string in the paragraph in an alert box.

Strings in our example are:
Apple
Oracle
Microsoft

HTML code
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
<html>
 <head><title>Bind & Unbind of Events: jQuery!</title></head>
 <body>
                      <p>Apple</p>
                      <p>Oracle</p>
                      <p>Microsoft</p>
 
                      <button>Unbind</button>
 
   <script type="text/javascript" src="script/jquery-1.8.1.min.js"></script>
   <script type="text/javascript" src="script/my_script.js"></script>
 </body>
</html>

Here we’re taking 3 paragraphs with some string in it.
And a button, to unbind the events associated with those paragraph texts!

jQuery code
my_script.js

1
2
3
4
5
6
7
8
9
10
11
$(document).ready( function() {
 
  $("p").bind( 'click', function() {
    alert( $(this).text()  );
  });
 
  $("button").bind( 'click', function() {
    $("p").unbind();
  });
 
});

Here p tag is associated with click event. So once the user clicks on the p tag, an alert box appears with the text present inside the paragraph which was being clicked.
button is also associated with click event. So once the user clicks on the button, all the events (click event in our example ) associated with the p tag gets removed, detached, unbinded.

We could also write the code in usual way: i.e., in convenience method as shown below

jQuery code
my_script.js

1
2
3
4
5
6
7
8
9
10
11
$(document).ready( function() {
 
  $("p").click( function() {
    alert( $(this).text()  );
  });
 
  $("button").click( function() {
    $("p").unbind();
  });
 
});

This code does the same thing as shown in binding method above.
Check with both the codes while you try it on your own.

Video Tutorial: jQuery Event Handling: Binding and Unbinding


[youtube https://www.youtube.com/watch?v=Q4EKDkBOuXU]

YouTube Link: https://www.youtube.com/watch?v=Q4EKDkBOuXU [Watch the Video In Full Screen.]



Binding and Unbinding of events would be helpful when we develop applications which does require all the or some events to be detached after some task is completed.

Also try other events like:
.dbclick()
.focus()
.focusin()
.focusout()
.hover()
.keypress
.keyup
.keydown
.mouseover()
.mouserin()
.mouseout()
.submit()
.select()
.scroll()
.trigger()
.toggle()
.load()
.unload() ..etc

Leave a Reply

Your email address will not be published. Required fields are marked *