0

I have a .menu div and when I click that it opens a modal and the .menu is changes to .menu-open. This works correctly, but I would like to close my modal when I click .menu-open, yet nothing happens.

Can you help me please? What's wrong with the code? Thank you!

$(document).ready(function() {
  $(".menu").click(function() {
    $('.menu-modal').show();
    $(".menu").switchClass("menu", "menu-open");
  });
});

$(document).ready(function() {
  $(".menu-open").click(function() {
    $('.menu-modal').hide();
    $(".menu-open").switchClass("menu-open", "menu");
  });
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
jouni
  • 3
  • 2
  • 2
    show your html as well – Swati Jan 13 '21 at 15:50
  • `$(".menu-open").click` only applies to elements that exist *at the time the code runs* - which yours don't as you add the class later. Use **event delegation**. `$(document).on("click", ".menu-open", function...` – freedomn-m Jan 13 '21 at 16:15
  • Does this answer your question? [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – freedomn-m Jan 13 '21 at 16:16
  • While not strictly "dynamically *created*" - see the link for details – freedomn-m Jan 13 '21 at 16:16

1 Answers1

0

Consider the following.

$(function() {
  function openMenu(){
    $('.menu-modal').show();
    $(".menu").switchClass("menu", "menu-open");
    $(this).off("click");
    $(this).click(closeMenu);
  }

  function closeMenu(){
    $(".menu-modal").hide();
    $(".menu-open").switchClass("menu-open", "menu");
    $(this).off("click");
    $(this).click(openMenu);
  }

  $(".menu").click(openMenu);
});

Since you're changing the Class, it is not in the DOM any longer and the original callback will not be run. We will need to unbind that callback using .off() and assign the new action.

You could also do the following.

$(function() {
  $("body").on("click", ".menu", function(){
    $('.menu-modal').show();
    $(".menu").switchClass("menu", "menu-open");
  }

  $("body").on("click", ".menu-open", function(){
    $(".menu-modal").hide();
    $(".menu-open").switchClass("menu-open", "menu");
  }
});

Using .on() will help delegate the callback to the selector.

See more:

The only caveat, if the Modal is covering the element that needs to be clicked, the click event will not be able to target that element.

Twisty
  • 30,304
  • 2
  • 26
  • 45