Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Larasou's avatar

Close a modal with the escape key

Good evening friends!

It's been a while that I search on the net a Vue.js directive that would allow me to close a modal when I press the key "Esc".

I tried full of directive like @ keyup.esc =" closeModalLogin ", @ keydown.esc =" closeModalLogin " etc ...

Do you have an idea ?

I'm using Tailwind CSS in my application

0 likes
6 replies
tykus's avatar

Key events can only be captured by focusable elements (inputs, buttons etc), if you add a tabindex to the modal div, you will get the focusable behaviour and can be targeted by the key event e.g.

<div class="modal" @keydown.esc="closeModalLogin" tabindex="0">
2 likes
ftiersch's avatar

But I think to capture the keydown event the element needs to be focussed so it wouldn't work as soon as you focus something else (like a form element inside the modal).

I wrote myself a little mixin for that exact usecase, maybe it helps:

export const Escapable = {
    created() {
        const escapeHandler = (e) => {
            if (e.key === 'Escape' && this.escapableVisible) {
                this.escapeHandler();
            }
        }

        document.addEventListener('keydown', escapeHandler);

        this.$once('hook:destroyed', () => {
            document.removeEventListener('keydown', escapeHandler);
        });
    }
}

Using it would work like this:

<script>
    import { Escapable} from "../mixins/Escapable";
   
    export default {
        mixins: [Escapable],
        data() {
            return {
                overlayVisible  : false,
            }
        },
        computed: {
            escapableVisible() {
                return this.overlayVisible;
            },
        },
        methods: {
            hide() {
                this.overlayVisible = false;
            },
            escapeHandler() {
                this.hide();
            },
        },
    }
</script>

It binds the escape key handler to the whole document but only actually hides the modal if it is currently visible.

DanielP's avatar
DanielP
Best Answer
Level 1

@tykus I'm sitting with the same problem. What solution did you choose in the end?

DanielP's avatar

Thank you. The vue component is a good idea. I'll implement it when we upgrade our Laravel version.

DaDo's avatar

hi bro, have you found a solution for this problem?

Please or to participate in this conversation.