The shift key is simply ignored after pressing another key, a bad switch key. How to determine when it will be released?

I have text input that currently becomes transparent when the user presses shift (keydown) and binds the listener to shift the keyboard up

t

$('#foo').keydown(function(){ if(event.which==16){ //make #foo transparent $(this).keyup(function(){ if(event.which==16){ //return #foo to its former glory $(this).unbind('keyup'); } }); }; }) 

This works great when no characters are pressed between pressing and releasing the toggle key. The problem is that when you shift down and another character is pressed, the shift key seems to be completely forgotten. When the shift key is released, the key does not start.

I tried running a "fake" keydown with the .which property set to 16 to push it in the right direction after pressing other characters, but to no avail.

Any suggestions would be greatly appreciated!

+6
source share
1 answer

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") { // make #foo transparent } else { // return #foo to its former glory } } }); 

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 .

+1
source

Source: https://habr.com/ru/post/948623/


All Articles