I have used this JavaScript below:
Adding to this for future readers.
Another way to dismiss the modal when clicking outside involved taking advantage of the bubbling nature of the javascript events.
In a typical modal HTML structure
-- Site content here
clicking on .modal will cause the click event to propagate like this .modal -> #modal-root -> body while clicking outside the modal will only go through #modal-root -> body.
Since we can stop the propagation of click events completely, and if that does not interfere with any other code, we only need to listen for click events in both .modal and #modal-root. A "modal-root" click will dismiss the modal, and a "modal" click will stop propagating the click event so never reaches the "modal-root".
For extra clarity, here's the code working in codepen.io: https://codepen.io/nbalaguer/pen/PVbEjm