Kater89 Kater89 - 4 months ago 7
jQuery Question

jQuery click not working after adding class but .on fires too soon to use

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!

Answer

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

Comments