Consider the following modal and the modal’s representation in the DOM.
When you click on anything in the modal, by default the “click” event is propagated from the element that is clicked to the document root. The element that is clicked is stored in event.target as the event is propagated. While propagating, any handlers that have been registered for the click event are invoked. When a handler is invoked, the event.currentTarget property is set to the element that registered the handler.
When a user clicks on the <img> or the save button or the cancel button, the handler that was registered for that element is invoked. After it is invoked there is no NEED for the event to propagate up the DOM (it has been handled). This is why we add the .stop modifier when registering those handlers.
Now, when the user clicks anything between the buttons and the backdrop <div> (exclusively), or the <h1> or the <input>, the click event is propagated up the DOM, eventually reaching the backdrop <div>. In these cases, we don’t want to close the modal – thus we don’t want the close() handler of the backdrop <div> to be invoked. In these cases, when the event hits the backdrop <div>’s handler, the event’s target property is set to the element that was clicked (like the <h1>) and the event’s currentTarget property is set to the backdrop <div>. Notice they are unequal. In other words,
event.target !== event.currentTarget
. The element that was clicked is not the same as the element that registered the handler.When the user clicks the backdrop <div> directly, we do want the modal to close. When this happens
event.target === event.currentTarget
. Therefore to ensure the backdrop <div>’s handler runs only when the user directly clicks the backdrop <div> we use the .self modifier when registering the handler on the <div> for the click event.