Monday, December 03, 2012

jQuery plugin: showKeyPressed

jQuery plugin: showKeyPressed

This plugin allows you to show the user the characters typed (temporarily) in a password field. The following would run on any password fields with the secure class.

Usage: $(":password.secure").showKeyPressed();

____________________

(function($){
    var ShowKeyPressedLib = {
        show: function (e, refNum, source)
        {
            e = e || window.event;
            var refId = "KP__" + refNum;
            var keycode = e.which;
            if (keycode == 32 ||
                keycode >= 41 && keycode <= 44 ||
                keycode >= 47 && keycode <= 111 ||
                keycode >= 146)
            {
                $(".keypressed").remove(); // Remove all previously shown first
                var coords = $(source).offset();
                var addPixels = 6 * source.value.length;
                $("<div></div>").attr("id", refId)
                                .css({ top: (coords.top - 20) + 'px', left: (coords.left + addPixels) + 'px' })
                                .addClass("keypressed")
                                .html(String.fromCharCode(keycode))
                                .appendTo("body");
            }
        },
        hide: function (refNum)
        {
            $("#KP__" + refNum).remove();
        },
        counter: 0
    }

    $.fn.showKeyPressed = function(){
     return $(this).bind('keypress', function(e){
            var refNum = ShowKeyPressedLib.counter++;
            ShowKeyPressedLib.show(e, refNum, this);
            setTimeout(function(){ ShowKeyPressedLib.hide(refNum) }, 999);
        });
    };
})(jQuery);