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!

JQuery Event Listener

In this post let’s look at how we can create an Event Listener using JQuery.

JQuery is a JavaScript Library and Event Listener is something that listens to an event or action to trigger a response.

First we’ll need to import JQuery as follows:

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

Next we’ll add a button with an id called awesome-button:

<button id="awesome-button">My Awesome Button</button>

Finally we’ll add some JQuery:

<script type="text/javascript">
	myBtn = $("#awesome-button");
	myBtn.on("click", sayHello);

	function sayHello() {
		console.log('You\'re awesome');
	}
</script>

What this does is, selects the html element with #awesome-button ID and ties it to myBtn variable. Next, we add an event listener to that variable using the on function which gets triggered on click event and runs the sayHello function.

That function, when it runs, logs You're awesome message in the browser’s console as follows:

Note: The browser’s console can be accessed by CMD+OPT+J shortcut.