loading...

Why can't I add an 'onkeydown' event to a DIV element?

twitter logo github logo ・1 min read

I am working on a game and I am trying to add movement but when I try to add an onkeydown event onto my div element, it doesn't work.

<div id="gameEvent">
    <canvas id="game" width="500" height="500"></canvas>
</div>
<script>
    var event = document.getElementById("gameEvent")
    // oncontextmenu works for some reason
    event.oncontextmenu = function() {
        return false
    }
    // this does nothing...
    event.onkeypress = function(e) {
        alert(e)
    }
</script>

Why?
Thanks,
Cheers!

twitter logo DISCUSS (10)
markdown guide
 

Hi,

onkeypress is only triggered for the 'active' field when a key is pressed.
You need to enable your element to receive focus. The trick is to add attr tabindex to #gameEvent.
(stackoverflow.com/questions/148361...

 
 

Why does it need to be tied to a <div>? Why don't you just make an event listener to window?

window.onkeypress = ...
 
 
Classic DEV Post from May 8 '19

Is “Defensive Programming” actually healthy?

I can’t solve this one, and I think I need the help of the DEV Community. So, a d...

PDS OWNER CALIN (Calin Baenen) profile image
I am a 13 (as of Oct 30 of 2019) yr/o developer (I have been developing mini-projects for 4, years now, since I was 9), who makes projects in languages like: Java, HTML, Python 3, JS, CSS, and C#.

Sore eyes?

dev.to now has dark mode.

Go to the "misc" section of your settings and select night theme ❤️