File Under: JavaScript

JavaScript Event – Keydown

This code was written based on a template by John Resig. The original can be found at John Resig’s addEvent function website.

The code, and the template, are referred to in Webmonkey’s JavaScript Events reference page. In this example, the onKeydown event fires when a key is pushed down while the target field has focus. Keydown fires as soon as the key is pressed down and only happens once (in other words, it does not continually fire like keypress). The distiction between keydown and keyup is that keydown fires before the value of the key is added to a field.

You can also set the target to be the entire window to catch the keydown event globally.

The Code

<html>

<head>

<script>

// addEvent function by John Resig:

// http://ejohn.org/projects/flexible-javascript-events/

function addEvent( obj, type, fn ) {

  if ( obj.attachEvent ) {

    obj['e'+type+fn] = fn;

    obj[type+fn] = function(){obj['e'+type+fn]( window.event );}

    obj.attachEvent( 'on'+type, obj[type+fn] );

  } else

    obj.addEventListener( type, fn, false );

}

</script>

</head>

<body>



<!-- HTML for example event goes here -->

<input id="mytext" type="text" />

<br /><div id="mydiv" style="border: 1px solid black; width: 100px; height: 100px; margin-top: 10px;"></div>



<script>

// Script for example event goes here

addEvent(document.getElementById('mytext'), 'keydown', function(event) {

	display_short('keydown: ' + event.keyCode);

});



function display_short(str)

{

	clearTimeout();

	document.getElementById('mydiv').innerHTML = str;

	if (str != '')

		setTimeout("display_short('')", 1000);

}

</script>

</body>



</html>

What it Looks Like