JavaScript onkeydown Event
You are Here:
JavaScript onkeydown Event
The onkeydown
event occurs when the user presses a keyboard key.
onkeydown Event as Attribute
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<input type="text" onkeydown="myFunction()">
<script>
function myFunction(){
alert("You pressed a key inside the input field");
}
</script>
</body>
</html>
Syntax
As Attribute
<element onkeydown = "JavaScript">
As Property
object.onkeydown = function(){
// code
};
Using Event Listener
object.addEventListener("keydown" , myScript);
onkeydown Event as Property
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<input type="text">
<script>
var x = document.getElementsByTagName("input")[0];
function myFunction(){
alert("You pressed a key inside the input field");
}
x.onkeydown = myFunction;
</script>
</body>
</html>
Using addEventListener() Method
Note: The addEventListener() method is not supported in Internet Explorer 8 and below.
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<input type="text">
<script>
var x = document.getElementsByTagName("input")[0];
function myFunction(){
alert("You pressed a key inside the input field");
}
x.addEventListener("keydown", myFunction);
</script>
</body>
</html>
onkeydown vs onkeypress vs onkeyup
Check out the difference between onkeydown vs onkeypress vs onkeyup in javascript.
Reminder
Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.
We are working to cover every Single Concept in JavaScript.
Please do google search for:
Join Our Channel
Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.
This channel is primarily useful for Full Stack Web Developer.