When you press shift, it will fire keydown events continuously until you release it, so your example will bind as many keyup handlers as there are keydown events. This is likely to cause all sorts of strange problems.
Instead, bind both keydown and keyup to the same handler and do your magic there:
$("#foo").on("keydown keyup", function (e) { if (e.which === 16) { if (e.type === "keydown") {
See jsFiddle test case .
However, if you lose input focus when you press shift and then release it, it will not work properly. One way to solve it is to bind instead of window :
var $foo = $("#foo"); var shiftPressed = false; $(window).on("keydown keyup", function (e) { if (e.which === 16) { shiftPressed = e.type === "keydown"; if (shiftPressed && e.target === $foo[0]) { $foo.addClass("transparent"); } else { $foo.removeClass("transparent"); } } }); $foo.on("focus blur", function (e) { if (e.type === "focus" && shiftPressed) { $foo.addClass("transparent"); } else { $foo.removeClass("transparent"); } });
See jsFiddle test case .
source share