Record Key Strokes Using JQuery

This is a simple post explaining how you could record key presses using JQuery and log those to the browser’s console.

The first step is to import JQuery as follows:

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>

The second step is to see how we could output something when a key is pressed on the keyboard.

<script type="text/javascript">
	$(document).on( "keyup", sayHello);
	function sayHello() {
		console.log('Hello! You pressed a key!');
	}
</script>

The above code adds an event listener to the document that listens for the event called keyup and then triggers the function called sayHello.

That function outputs some message in the browser’s console (which can be accessed by OPT+CMD+J).

This code can be modified to get specific key codes as follows:

<script type="text/javascript">
	$(document).on( "keyup", sayHello);
	function sayHello(e) {
		console.log(e.keyCode);
	}
</script>

Now if you press a key, the browser logs the keycode of that particular key. For example, hitting the enter key will output 13 in the browser’s console. Hitting A key will output 65 and so on. You get the idea!

Leave a comment