Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript/jQuery Keypress logging

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?

like image 990
CLiown Avatar asked Feb 19 '10 15:02

CLiown


People also ask

How does jQuery detect keyboard press?

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.

What is e keycode === 13?

Keycode 13 is the Enter key.

Is Onkeypress deprecated?

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.

How does jQuery handle Enter key events?

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.


1 Answers

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.

like image 68
user113716 Avatar answered Sep 28 '22 04:09

user113716