In your first example you are putting on click event to document, not to the modal window itself. Reason your first block of code works is because it works even if you add elements dynamically later. If you want your second block of code to work as well, you need to make sure that you already have the HTML fully loaded before trying to add click event.
Check out .on() documentation
The way I figure it for myself is that your first block of code is going to put click event on whole document.
- Each time you click somewhere it will try to do a match of which
element was clicked.
- If you click somewhere random it will not fire function, but if you
click on the .close_modal_window it will find a match on the selector
and fire up function you have there.
Your second block of code does the same thing but differently.
- Second way is faster, because you don't watch for every
single click on whole page and then do the matches.
- It will tie click function directly to .close_modal_window and will
only fire up once you click on it.
- However in order for this to work you have to already have HTML for
.close_modal_window on the page, then run this code.
Also in this case if you add more classes with same name, it will not work unless you run this part of code again, so you have to be careful if you plan on adding more HTML elements with same class and have the click working on it