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!

2 Answers 2

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()

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! That is much easier :) I figured it would be something easy like that.
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');
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.