Search code examples
javascriptdom-eventsonkeydown

Is it possible to add keydown event on anything other than an input


<div type="text" id="demo">
Hi
</div>

<script>
document.getElementById("demo").addEventListener("keypress", myFunction);

function myFunction() {
    document.getElementById("demo").style.backgroundColor = "red";
}
</script>

I'm trying to change the color of the div demo when a key is pressed


Solution

  • you can do this by add attribute tabindex="1" to the div

    **update : ** here is a js fiddle

    https://jsfiddle.net/dsm97po9/

    <div tabindex="1" id="demo">
    

    try it and tell me