Close modals and dropdown when ESC is pressed.

This commit is contained in:
Fabio Manganiello 2023-05-05 20:46:42 +02:00
parent e9e59c857a
commit 6e939bbe62
Signed by untrusted user: blacklight
GPG key ID: D90FBA7F76362774
2 changed files with 29 additions and 1 deletions

View file

@ -1,5 +1,6 @@
<template>
<div class="modal-container fade-in" :id="id" :class="{hidden: !isVisible}" :style="{'--z-index': zIndex}" @click="close">
<div class="modal-container fade-in" :id="id" :class="{hidden: !isVisible}"
:style="{'--z-index': zIndex}" @click="close">
<div class="modal" :class="$attrs.class">
<div class="content" :style="{'--width': width, '--height': height}" @click="$event.stopPropagation()">
<div class="header" v-if="title">
@ -94,6 +95,13 @@ export default {
else
this.show()
},
onKeyUp(event) {
event.stopPropagation()
if (event.key === 'Escape') {
this.close()
}
},
},
mounted() {
@ -107,10 +115,15 @@ export default {
self.isVisible = visible
}
document.body.addEventListener('keyup', this.onKeyUp)
this.$watch(() => this.visible, visibleHndl)
this.$watch(() => this.isVisible, visibleHndl)
},
unmounted() {
document.body.removeEventListener('keyup', this.onKeyUp)
},
updated() {
this.prevVisible = this.isVisible
if (this.isVisible) {

View file

@ -94,6 +94,21 @@ export default {
this.$emit('click')
this.visible ? this.close() : this.open()
},
onKeyUp(event) {
event.stopPropagation()
if (event.key === 'Escape') {
this.close()
}
},
},
mounted() {
document.body.addEventListener('keyup', this.onKeyUp)
},
unmounted() {
document.body.removeEventListener('keyup', this.onKeyUp)
},
}
</script>