close dialog on click outside

This commit is contained in:
Nolan Lawson 2018-02-04 15:04:20 -08:00
parent 2e2c278dee
commit 1152d96289
1 changed files with 16 additions and 7 deletions

View File

@ -1,6 +1,6 @@
<div class="dialog-wrapper" ref:node> <div class="dialog-wrapper" ref:node>
<div class="close-dialog-button-wrapper"> <div class="close-dialog-button-wrapper">
<button class="close-dialog-button" aria-label="Close dialog" on:click="onCloseButtonClicked()"> <button class="close-dialog-button" aria-label="Close dialog" on:click="close()">
<span aria-hidden="true">&times;</span> <span aria-hidden="true">&times;</span>
</button> </button>
</div> </div>
@ -38,11 +38,8 @@
font-size: 48px; font-size: 48px;
color: var(--button-primary-text); color: var(--button-primary-text);
} }
:global(dialog.modal-dialog::backdrop) { :global(dialog::backdrop, .backdrop) {
background: rgba(51, 51, 51, 0.8); background: rgba(51, 51, 51, 0.9) !important; /* TODO: hack for Safari */
}
:global(dialog.modal-dialog + .backdrop) {
background: rgba(51, 51, 51, 0.8);
} }
</style> </style>
<script> <script>
@ -62,6 +59,17 @@
} }
}) })
this.registration = this.register() this.registration = this.register()
this.onDocumentClick = (e) => {
let dialog = this.getDialogElement()
if (!dialog.open) {
return;
}
if (e.target !== dialog) {
return;
}
this.close() // close when clicked outside of dialog
}
document.body.addEventListener('click', this.onDocumentClick);
}, },
methods: { methods: {
async register() { async register() {
@ -75,9 +83,10 @@
await this.registration await this.registration
this.getDialogElement().showModal() this.getDialogElement().showModal()
}, },
onCloseButtonClicked() { close() {
this.getDialogElement().close() this.getDialogElement().close()
document.body.removeChild(this.getDialogElement()) document.body.removeChild(this.getDialogElement())
document.body.removeEventListener('click', this.onDocumentClick);
}, },
getDialogElement() { getDialogElement() {
return this.refs.node.parentElement return this.refs.node.parentElement