I would like to be able to log the key presses on a specific page, trying to implement an 'Easter egg' type functionality where when the correct keys are pressed in the correct order it triggers and event.
Can anyone give me any pointers?
The keypress() method in jQuery triggers the keypress event whenever browser registers a keyboard input. So, Using keypress() method it can be detected if any key is pressed or not.
Keycode 13 is the Enter key.
Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes.
To trigger a click button on ENTER key, We can use any of the keyup(), keydown() and keypress() events of jQuery. keyup(): This event occurs when a keyboard key is released. The method either triggers the keyup event, or to run a function when a keyup event occurs.
Well, even though another answer has been accepted, I'm going to throw one out there anyway.
$(document).ready(function() {
var easterEgg = 'egg';
var eggLength = easterEgg.length;
var keyHistory = '';
var match;
$(document).keypress(function(e) {
keyHistory += String.fromCharCode(e.which)
match = keyHistory.match(easterEgg);
if(match) {
alert(match);
keyHistory = match = '';
} else if (keyHistory.length > 30) {
keyHistory = keyHistory.substr((keyHistory.length - eggLength - 1));
}
});
});
When you ultimately type 'egg' (for this example), you will get an alert, and the key history will reset.
EDIT: Updated the code to truncate the string if it gets too long.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With