TheKingPinMirza
TheKingPinMirza

Reputation: 8922

jQuery - how to destroy/unbind click event

In my application, i have calendar icon so when it is clicked the calendar pop up shows.

So, I have the following jQuery code which hides the section when i clicked anywhere of <Div> matching with css class.

<script>
$(document).ready(function(){
    $(".myContent").click(function () {
        $(".calendar").hide();
    });
});
</script>

However, the issue i am facing is it works fine for the first time

i.e. Click on Calendar Icon shows calendar popup.. than click on anywhere inside Div hides calendar pop-up.

However, When i reclick on Calendar icon than it does not show calendar popup unless i refresh the whole page.

I am guessing that i need to unbind click event but not sure how... Any help please?

Upvotes: 0

Views: 1804

Answers (5)

brroshan
brroshan

Reputation: 1650

Not sure about your angularjs but try this:

$(document).ready(function(){
     $(document).on("click", ".myContent, function () {
           $(".calendar").hide();
     });

     $("#CalendarSettings").on("click", function()  {
           $(".calendar").show();
     });
  });

Upvotes: 0

Barmar
Barmar

Reputation: 780994

Use event.stopPropagation to keep the click on the calendar icon from bubbling out to .myContent:

$("#calendar_icon").click(function(e) {
    e.stopPropagation();
    $(".calendar").show();
});

Upvotes: 2

Alliswell
Alliswell

Reputation: 1583

Try:

<script>
$(document).ready(function(){
    $('body').on('click', '.myContent', function() {
        $(".calendar").hide();
    });
});
</script>

Upvotes: 0

madoxdev
madoxdev

Reputation: 3880

To unbind You can use off like:

$(".myContent").off('click');

Please refer: jQuery Documentation for more details.

Upvotes: 1

Taplar
Taplar

Reputation: 24965

You can use off.

var handler = function(){ /* whatever */ };
$(selector).on('click', handler);
$(selector).off('click', handler);

Alternatively if you only want it to happen at most one time...

$(selector).one('click', function(){ /* whatever */});

Upvotes: 0

Related Questions