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

testy's avatar

Vue.js listen for Key Events on div

Is there an way to listen for space or other key OUTSIDE from input fields?

Something like

<div @keyup.space="method()">

</div>

0 likes
5 replies
tykus's avatar

Don't think Vue supports this. Global keypress events can be handled by attaching listeners after the component is created

new Vue({
    created: function () {
            window.addEventListener('keyup', this.myMethod())
    },
    methods: {
        myMethod: function () {
            // stuff
        }
    }
    ...
});
1 like
nikocraft's avatar

Hi

how to detect what key was pressed? using this:

        myMethod: function (event) {
            console.log('key pressed: ' + event.which)
        }

does not work, it produces:

Error in mounted hook: "TypeError: Cannot read property 'which' of undefined"

Qrzy's avatar

@maxnb It's due to an error in @tykus's answer. The addEventListener method takes a function as a second argument, not it's result. Simply remove the parentheses:

new Vue({
    created: function () {
            window.addEventListener('keyup', this.myMethod)
    },
    methods: {
        myMethod: function () {
            // stuff
        }
    }
    ...
});
3 likes
rumm.an's avatar

div is not focusable element by default, you can make it focusable by tabindex attribute set it to 0. Once you make it focusable, you can focus on div element. And, when you have focus on element, all key events will be triggered.

<div @keyup.space="action" tabindex="0">
     ...
<\div>
4 likes

Please or to participate in this conversation.