EN
JavaScript - onkeypress event example
0
points
In this article, we would like to show you onkeypress
event example in JavaScript.
Quick solution:
var myElement = document.querySelector('#my-element');
myElement.addEventListener('keypress', function() {
console.log('onkeypress event occurred.');
});
or:
<input type="text" onkeypress="handleKeypress()">
or:
var myElement = document.querySelector('#my-element');
myElement.onkeypress = function() {
console.log('onkeypress event occurred.');
};
Practical examples
There are three common ways how to use onkeypress
event:
- with event listener,
- with element attribute,
- with element property.
1. Event listener based example
In this section, we want to show how to use onkeypress
event on input
element via event listener mechanism.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<p>Type something: </p>
<input type="text" id="my-input">
<script>
var myInput = document.querySelector('#my-input');
myInput.addEventListener('keypress', function() {
console.log('onkeypress event occurred.');
});
</script>
</body>
</html>
2. Attribute based example
In this section, we want to show how to use onkeypress
event on input
element via attribute.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<p>Type something: </p>
<input type="text" onkeypress="handleKeypress()">
<script>
function handleKeypress(){
console.log('onkeypress event occurred.');
}
</script>
</body>
</html>
3. Property based example
In this section, we want to show how to use onkeypress
event on input
element via property.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<p>Type something: </p>
<input type="text" id="my-input">
<script>
var myInput = document.querySelector('#my-input');
myInput.onkeypress = function() {
console.log('onkeypress event occurred.');
};
</script>
</body>
</html>