We use the bind() method to subscribe to events with jQuery. However, you may need to remove these subscriptions again for various reasons, to prevent the event handler to be executed once the event occurs. We do this with the unbind() method, which in its simplest form simply looks like this:
$("a").unbind();
This will remove any event handlers that you have attached with the bind() function. However, you may want to only remove event subscriptions of a specific type, for instance clicks and doubleclicks:
$("a").unbind("click doubleclick");
Simply separate the event types with a comma. Here is a more complete example, where you can see it all in effect: <a href="javascript:void(0);">Test 1</a>
<a href="javascript:void(0);">Test 2</a>
<script type="text/javascript">
var msg = "Hello, world!";
$(function()
{
$("a").bind("click", function() {
$("a").unbind("click");
alert("First and only message from me!");
});
});
</script>
In this little example, we subscribe to the click event of all links. However, once a link is clicked, we remove all the subscriptions and alert the clicker about it. The event handler will no longer be activated by the links.
jQuery allows you to subscribe to the same event type more than one time. This can come in handy if you want the same event to do more than one thing in different situations. You do it by calling the bind() method for each time you want to attach a piece of code to it, like this:
<a href="javascript:void(0);">Test 1</a>
<a href="javascript:void(0);">Test 2</a>
<script type="text/javascript">
var msg = "Hello, world!";
$(function()
{
$("a").bind("click", function() {
alert("First event handler!");
});
$("a").bind("click", function() {
alert("Second event handler!");
$("a").unbind("click");
});
});
</script>
However, this opens up for the possibility that once you unbind an event, you may be removing event subscriptions used a whole other place in your code, which you still need. If you try the example, you will see the result of this - when you click a link, all of the event subscriptions are removed. jQuery allows you to specify a secondary argument, which contains a reference to the specific handler you would like to remove. This way, we can make sure that we only remove the event subscription we intend to. Here's an example:
<a href="javascript:void(0);">Test 1</a>
<a href="javascript:void(0);">Test 2</a>
<script type="text/javascript">
var msg = "Hello, world!";
$(function()
{
var handler1 = function()
{
alert("First event handler!");
}
var handler2 = function()
{
alert("Second event handler!");
$("a").unbind("click", handler2);
}
$("a").bind("click", handler1);
$("a").bind("click", handler2);
});
</script>
By specifying handler2 as the secondary parameter, only this specific event handler is removed. Try the example. The secondary message is only displayed the first time you click the link.
Blogger Comment
Facebook Comment