Search code examples
jquerypasswordskeypress

Keypress CTRL is pressed in Jquery?


I want to make something like when user press and hold CTRL key on keyboard to show him entered password and when he release CTRL to hide the password on input?

This is what i have for now

$(document).keypress(function (event) {

            var keycode = (event.keyCode ? event.keyCode : event.which);
            if (keycode == '13') {
                $("#password").prop("type", "text");
            }
            else {
                $("#password").prop("type", "password");
            }

        });

This is what I made it for ENTER, but i i want to check if Ctrl is pressed, and when not?


Solution

  • You can check the ctrlKey property of the event in keydown. It will be true if the CTRL key is pressed. You then need to reset the type back to password on the keyup event.

    $(document).keydown(function (event) {
        $("#password").prop("type", event.ctrlKey ? 'text' : 'password');
    }).keyup(function() {
        $("#password").prop("type", 'password');
    });
    

    Example fiddle