I am building a settings menu for my site which would appear as a popup. Currently, I can open/close this popup by clicking on the button linked to it.However, I would like to implement a way to close this popup/div by simply clicking outside the popup.
I believe JavaScript can complete this action, unfortunately, I'm am not yet well versed in using this language.
Does anyone have a solution that satisfies my needs, this is what i am working with...
Thanks in advance :)
var settingsmenu = document.querySelector(".settings-menu");
function settingsMenuToggle(){
settingsmenu.classList.toggle("settings-menu-height");
}
.settings-menu{
position: absolute;
width: 90%;
max-width: 350px;
background: var(--color-light);
box-shadow: 0 0 10px rgba(0, 0, 0, 0.4);
border-radius: 4px;
overflow: hidden;
top: 84px;
right: 9%;
max-height: 0;
transition: max-height 0.3s;
}
.settings-menu-height{
max-height: 300px;
}
.settings-menu-inner{
padding: 20px;
}
<div class="create">
<figure onclick="settingsMenuToggle()">
<button>Open Popup</button>
</figure>
</div>
<div class="settings-menu">
<div class="settings-menu-inner">
<figure>
<img src="https://images.macrumors.com/t/Y_7ongT7QQ-k0uYwUE4uCoCO3TI=/800x0/article-new/2019/08/apple-settings-icon-19.jpg-250x250.jpg?lossy" width="100" height="100">
<h3>This is a popup</h3>
</figure>
</div>
</div>
It's quite easy, you wrap your current popover in one extra div; so if you currently had:
<div class="settings-menu">
...stuff...
</div>
then you turn that into:
<div class="popover-backplate">
<div class="settings-menu">
...stuff...
</div>
</div>
Next you add some CSS like:
.popover-backplate {
position: fixed;
width: 100vw;
height: 100vh;
background-color: red;
opacity: 0.5;
}
If that worked then there should be a semi-transparent red overlay over the entire page (everything outside the popover anyway). If that is not the case then you may have to add a z-index
property to both settings-menu
and/or popover-backplate
.
Once the visual part works, all that's left is adding a bit of javascript under popover-backplate
s onclick
-event, which calls your popover_close()
-function (whatever it is called).