I use the lightcase plugin for modal windows. When I click on a particular button, a window pops up. The plugin inserts a specific layout at the end of the body , which appears only after clicking on the button, i.e. A modal window appears. I want to make my button close the modal window. For this, I hang up the click event handler for this button in $(document).ready(...) , but the click event of the button does not work even if a modal window is open. How do I declare an event handler in this case?

This code is inserted into the contents of the modal window:

 <div class="edit editUserName"> ... <div class="popup" id="editNamePopup"> <form> ... </form> <div class="close"> </div> 

...

 <script> $(document).ready(function(){ $('.editUserName').click(function(){ lightcase.start(); }); $('.popup .close').click(function(){ //Вот эта функция и не выполняется }) }) <script> 
  • can you make an example on jsfiddle? - Grundy

2 answers 2

Option 1:

If after pressing the button for displaying a modal window, the code of the modal window is added to the page code, the event may not be executed, since it does not work for new (dynamically created) elements.

Therefore, instead of the code:

 $('.popup .close').click(function(){ //Вот эта функция и не выполняется }) 

Use code:

 $(document).on("click",".popup .close", function(){ /*.....*/ }) 

Option 2:

If the plug-in modal window code is inserted directly onto the page, and not after clicking the show modal window button, you can use the following code:

 $(".popup .close").on("click", function(){ /*.....*/ }) 

UPD :

The original plugin inserts the form code into the lightcase-contentInner after clicking on the form display button ( example of ajax modal window ), so if you want to position the button in the form you are creating, use Option 1 suggested above.

    When the document is ready, the button does not exist yet, so you need to use not "click", but "live":

     $('.popup .close').live("click", function(){ //Вот эта функция и не выполняется }) 

    http://jquery-docs.ru/Events/live/

    http://api.jquery.com/live/

    • 3
      live version deprecated: 1.7, removed: 1.9 , so it's better on but it all depends on the version of the library used - Grundy
    • Indeed, what a non - engaging I am - Andrew Zakharov