Javascript DOM onkeydown Event via addEventListener() method

Introduction

In JavaScript, using the addEventListener() method:

object.addEventListener("keydown",
       myScript);

This example uses the addEventListener() method to attach a "keydown" event to an input element.

Press a key inside the text field to set a red background color.

View in separate window

<!DOCTYPE html>
<html>
<body>
<input type="text" id="demo">
<script>
document.getElementById("demo").addEventListener("keydown", myFunction);

function myFunction() {/*  w ww .  j  a  va 2 s.c  o  m*/
  document.getElementById("demo").style.backgroundColor = "red";
}
</script>

</body>
</html>
Bubbles:
Cancelable:
Event type:
Supported HTML tags:












Yes
Yes
KeyboardEvent
All HTML elements,
EXCEPT:
<base>,
<bdo>,
<br>,
<head>,
<html>,
<iframe>,
<meta>,
<param>,
<script>,
<style>, and
<title>



PreviousNext

Related