[SalesForce] Close Lightning Modal by clicking anywhere outside of it

Just wondering whether this is possible? i.e. once a modal is open, close it by clicking anywhere on the grey backdrop?

I've tried invoking my custom close-modal function via:
– Adding onclick to the slds-backdrop div
– Adding onblur to the slds-modal__container div
– Adding onclick to the slds-modal (just wanted to see whether this would work)

None of these seem to work.

Best Answer

It is possible, my approach is/was to create a static resource with an eventlistener on clicks outside of the scope of my modal. i then referenced the static resource in my lightning component and on click I simply change the classes (add/remove)

For my actual modal, I have 1 eventlistener which on click I trigger an event.stopPropagation(); for example:

Object.addEventListener('click', function(e){
    e.stopPropagation();
});

and for the rest of the component:

document.addEventListener('click', function(e){
    closeModal();
});

in the end, I endup having a component:

<aura:component implements="interfaces" access="global" >
    <ltng:require 
        scripts="{!$Resource.MyJsResource+ '/File.js'}" />

    <div class="slds">
    <div aria-hidden="true" role="dialog" class="slds-modal slds-modal--prompt slds-fade-in-hide" aura:id="modaldialog">
        <div class="slds-modal__container"> 
...