0

I am adding a class to a div similar to below:

$("#mainPopup").click(function() {
    $('.myPopupBox').show();
    $(this).addClass('popupMinus');
});

And then later have this click function based on the class added dynamically above:

$('body').on('click', '.popupMinus', function () {
  $('.myPopupBox').hide();
  $(this).removeClass('popupMinus');
});

I know that I have to use .on because the class is being added dynamically. (here is the article I am referencing) but when I have this code above, it fires the show and then the hide all at once so nothing looks like it is happening.

Helpful information:

  • I do have everything is a document $(document).ready(function() { but I have tried putting the second function outside of it.
  • I tried playing with the order of the functions. Didn't make a difference.
  • If I don't include the second function (with the hide feature) then the first one with the show works perfectly.
  • I have tried using delays - doesn't help

I'm sure that I am doing something dumb but can't find anything online that helps.

Thanks!

Community
  • 1
  • 1
Kater89
  • 93
  • 9

2 Answers2

3

You are over complicating this. You don't need to have 2 separate events. You are clicking on one button, so leave it as one click function, and then use jQuery's .toggle() to toggle the elements visibility.

$(document).on('click', '#mainPopup', function(){
    $('.myPopupBox').toggle();
    $(this).toggleClass('popupMinus');
});

Documentation:

.toggle() - http://api.jquery.com/toggle/

.toggleClass() - http://api.jquery.com/toggleclass/

Note - it should also be noted that by using $(document).on() you do not need to wrap it inside $(document).ready()

Adjit
  • 10,134
  • 12
  • 53
  • 98
1

The problem is that clicking calls to 2 functions, you have to merge them in one function. Like this:

$('body').on('click', '.popupMinus', function () {
  $('.myPopupBox').toggle();
  $(this).toggleClass('popupMinus');
});
ABE
  • 734
  • 2
  • 9
  • 21