BPD1 BPD1 - 22 days ago 6
Javascript Question

How to find previously pressed key in javascript

I want to find what key was pressed previously using Javascript using approach which is cross-browser compatible.

Answer

I guess you are looking for a solution like this.

HTML:

<textarea rows="4" cols="50">
    Just start typing here ... 
</textarea>

<p>
    This is the previously pressed key: <span id="output"> </span>
</p>

JavaScript (jQuery):

var pressedKeys = [];
var lastKey;

$('textarea').on('keydown', function(e) {
    pressedKeys.push(e.key);
    lastKey = pressedKeys[pressedKeys.length - 2]

    $('#output').html(lastKey);
});

Watch it on CodePen here: http://codepen.io/MarkBuskbjerg/pen/Yppbrg