'JQuery document click unbind removes all children click events

I add a click event to a specific element using JQuery's live():

 $('#foo').live('click');

Later, I add bind() to document:

 $(document).bind('click');

Once document is clicked, I unbind document click:

 $(document).unbind('click');

This caused problem: my #foo element no longer has a click event because it is document's child. How can I remove document's click leaving #foo element untouched?

Here is demo: http://jsfiddle.net/zS2Mt/2/



Solution 1:[1]

You can use events namespaces

Namespaced Events

$(document).bind('click.documentEvent');

$(document).unbind('click.documentEvent');

Solution 2:[2]

Here is one approach. You could just have two click events and check the target of the click event when clicking on the document and verify that it is not the link. I'm sure there is a better way to do this but it works:

var clicked = "I am clicked. Click outside!";
var unclicked = "Click me now!";

$('#foo').click(function() {
   if($(this).html() == unclicked) {
       $(this).html(clicked);
   }      
});

$(document).click(function(e) {
   if(e.target != $('#foo')[0] && $('#foo').html() == clicked) {
       $('#foo').html(unclicked);
   }      
});

http://jsfiddle.net/zS2Mt/3/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Catalin
Solution 2