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 = ...
 

This would be impractical, what if I wanted multiple divs to listen to a keypress event, but I didn't all want them to be active at once?

 
 
Classic DEV Post from Mar 1

What was your win this week?

Got to all your meetings on time? Started a new project? Fixed a tricky bug?

PDS OWNER CALIN (Calin Baenen) profile image
I am a 13 (as of Oct 30 of 2019) yr/o developer who makes projects in languages like: Java, HTML, Python, JS, CSS, C, and am working on learning C++, and C#.

dev.to is where software developers stay in the loop and avoid career stagnation.

Sign up (for free)