What is difference between these two codes ?
$(document).on(\'click\', \'.close_modal_window\', function(){
alert(\"window closed\");
});
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.
Your second block of code does the same thing but differently.
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
The difference between the two is that the second version of your code only binds the click function to elements with a class of close_modal_window that are on the page when it loads. The first version of your code binds the click action to any element on the page that ever appears with the close_modal_window class, even if it appears dynamically after the page loads.
first
it works if you have static html which you write like
<div id="divID">My div</div>
second
it works if you make/create dynamic html like
var myDiv ='<div id="divID">My div</div>'
and then you append it in some element like
$('#someid').append(myDiv )
the second approach is called event delegation
Above are two examples with button's click event:
<button>click me</button>
Look the difference.
Here is an example with delegation:
http://jsfiddle.net/xtz1np6d/
and here one without delegation:
http://jsfiddle.net/ketme18a/
As you can see, elements created dinamically, aren't in the context when the function was created, and for that, they don't have any function assigned.
I super recommend this lecture: Understanding Event Delegation
But be cautious, had one time that I used event delegation and it crushed my niceScroll-plugin in iPad.