Definition:
An onkeypress event occurs when a user presses a key on a webpage.
The webpage can react immediately and change the text, color, or style.
For example: When you type any key inside a textbox and the text color or style changes while typing, it is called an onkeypress event.
Now you will clearly understand with the help of the flowchart.
Start
|
v
User presses a key on the keyboard
|
v
Browser detects the onkeypress event
|
v
Is there a function assigned?
|
|-- Yes --> Run the function
| |
| v
| Character input or action performed
| |
| v
| End
|
|-- No --> Nothing happens
|
v
End
Syntax:
<element onkeypress="functionName()"></element>
Example:
<!DOCTYPE html>
<html>
<body>
<input type="text" onkeypress="showMessage()" placeholder="Press any key">
<script>
function showMessage() {
console.log("A key was pressed!");
}
</script>
</body>
</html>
Output:
if you want this message to appear again and again, it will also show in the browser console (F12) each time you press a key.
