A key event is triggered in response to some key action that occurs, like pressing the Enter key. In order to respond to a key event, a handler function must be set to be called when the event occurs. In the code below, I have created 3 elements to display 3 types of events: Key Down, Key Up, and Key Press. Each of the 3 elements is a simple div that I have styled. Then I set the events that each element will report to and attach an anonymous function to handle the event. Each of the handler functions sets the inner text (i.e. the innerHTML).
Each key for a key event has a specific key code associated with it. Consult our table of JavaScript key codes to find a desired key code.
<!DOCTYPE html> <html> <head> <title>XoaX.net's Javascript</title> </head> <body> <script type="text/javascript" src="KeyEvents.js"></script> </body> </html>
var qBody = document.getElementsByTagName("body")[0]; // Key Down Events var qKeyDownEventDiv = document.createElement("div"); qKeyDownEventDiv.style.backgroundColor = "#ffaaaa"; qKeyDownEventDiv.style.width = "200px"; qKeyDownEventDiv.style.height = "20px"; qKeyDownEventDiv.style.margin = "5px"; qKeyDownEventDiv.style.color = "#404040"; qKeyDownEventDiv.innerHTML = "No Event Yet<br />"; document.onkeydown = function(e) { qKeyDownEventDiv.innerHTML = "Key Down: Key Code = " + event.keyCode + "<br />"; }; qBody.appendChild(qKeyDownEventDiv); // Key Up Events var qKeyUpEventDiv = document.createElement("div"); qKeyUpEventDiv.style.backgroundColor = "#aaffaa"; qKeyUpEventDiv.style.width = "200px"; qKeyUpEventDiv.style.height = "20px"; qKeyUpEventDiv.style.margin = "5px"; qKeyUpEventDiv.style.color = "#404040"; qKeyUpEventDiv.innerHTML = "No Event Yet<br />"; document.onkeyup = function(e) { qKeyUpEventDiv.innerHTML = "Key Up: Key Code = " + event.keyCode + "<br />"; }; qBody.appendChild(qKeyUpEventDiv); // Key Press Events var qKeyPressEventDiv = document.createElement("div"); qKeyPressEventDiv.style.backgroundColor = "#aaaaff"; qKeyPressEventDiv.style.width = "200px"; qKeyPressEventDiv.style.height = "20px"; qKeyPressEventDiv.style.margin = "5px"; qKeyPressEventDiv.style.color = "#404040"; qKeyPressEventDiv.innerHTML = "No Event Yet<br />"; document.onkeypress = function(e) { qKeyPressEventDiv.innerHTML = "Key Press: Key Code = " + event.keyCode + "<br />"; }; qBody.appendChild(qKeyPressEventDiv);
© 20072024 XoaX.net LLC. All rights reserved.