"keypress" listener not working

I did what the event said and it didn’t change color

The <div> element does not accept key press events.

One way of getting it to work is making the <div> editable:
<div id="Dom-Two" contenteditable="true">Object-Two</div>

Then after you put the cursor (‘caret’) into the text, your code will work when a key is pressed.

Note the keypress event is deprecated:

1 Like

You don’t need to make the div editable to get keyboard events, just focusable. You can do that using the tabindex attribute.

<div id="Dom-Two" tabindex="0">Object-Two</div>

The you can click on the div to focus it and press a key.

1 Like

I thought it mean’t you can press any key and it will change color, didn’t know there was more conditions to make it work. are there any events related to just pressing any key, without adding what you mentioned, triggering the event or no?


The others in the thread are better placed to answer this than me but maybe I can nudge the conversation a little :slight_smile:

It would help if we knew what exactly this is for as it seems to me you just want the div to turn blue when any key is pressed? At the moment you are only listening to the div and there won’t be any key presses on that div to detect.

Just to see if this is what you meant then change this code:


To this:


If that does what you want then hopefully someone else will jump in with the non deprecated version. :slight_smile:


document.getElementById('DomTwo').style.color = "blue";

I think you missed the code in the first post as DomTwo is the variable for the element reference. There is no html element called DomTwo :slight_smile:

This was my thinking for what @Growly seemed to be asking:

let DomTwo = document.getElementById("Dom-Two");

document.body.addEventListener("keydown", function () {
  DomTwo.style.color = "blue";

Just for checking it I put it a codepen for easier testing.

I changed it to a toggle class anyway so that any key pressed toggles the color on and off.

I can see no use case for this though in its present format so @Growly will need to expand on what his requirements are :slight_smile:

1 Like