0

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?

immirza
  • 6,814
  • 6
  • 49
  • 76

5 Answers5

2

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();
});
Barmar
  • 669,327
  • 51
  • 454
  • 560
  • What is #calendar_icon in your example? – immirza May 22 '15 at 12:06
  • It's the ID of the calendar icon that you click on to display the calendar. – Barmar May 22 '15 at 12:07
  • I already have stopPropagation() in my html line – immirza May 22 '15 at 12:15
  • stopPropagation() still not solved my issue.. not sure im using it in righ way or not.. – immirza May 22 '15 at 13:05
  • I don't know Angular, so I can't help you with that. – Barmar May 22 '15 at 15:22
1

To unbind You can use off like:

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

Please refer: jQuery Documentation for more details.

madoxdev
  • 3,452
  • 1
  • 22
  • 39
0

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 */});
Taplar
  • 24,556
  • 4
  • 20
  • 34
0

Try:

<script>
$(document).ready(function(){
    $('body').on('click', '.myContent', function() {
        $(".calendar").hide();
    });
});
</script>
Alliswell
  • 1,425
  • 19
  • 34
0

Not sure about your angularjs but try this:

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

     $("#CalendarSettings").on("click", function()  {
           $(".calendar").show();
     });
  });
brroshan
  • 1,600
  • 15
  • 19