Javascript Element How to - Handle key press event for div








Question

We would like to know how to handle key press event for div.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
function startGame() {<!--from  ww w. ja v  a2  s  .c  o  m-->
    document.getElementById("2").innerHTML = ('Testing!');
}
window.onload = function() {
    document.getElementById("1").onkeypress = startGame;
}

</script>
</head>
<body>
  <div class="title" name="Game Title" id="0">Game Title</div>

  <div tabindex="0" class="gamecontainer" name="Game Container" id="1">
    Press any key to start.</div>
    
  <div class="gamemonitor" name="Game Monitor" id="2">Game Monitor:</div>
</body>
</html>

The code above is rendered as follows: