Forum Moderators: open

Message Too Old, No Replies

Using keyup to get the last character typed

specifically finding a capital letter

         

csdude55

1:56 am on Nov 28, 2021 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



How can I find the last character entered instead of the Shift key?

Here's what I have; I'm using jQuery, but I'm not sure that it really matters:

$('#str').on('keyup', function(e) {
alert(e.key);
});


When they type, for example, "D", e.key returns Shift instead of D!

I get the same result with 'keydown'.

Any suggestions on how to get the D instead of Shift?

NickMNS

6:22 am on Nov 28, 2021 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Add a variable and store the last key stroke. If the e.key === "Shift" don't update the variable


const input = document.querySelector('input');
let key;
input.addEventListener("keyup", (e) => {
key = e.key !== "Shift" ? e.key : key
console.log(key, e.key)
})


I'm not sure this completely solves the problem because a Shift D will return D twice. But that can be managed in the logic of your final script, for example by setting the value to "null" instead of not updating.

lucy24

6:18 pm on Nov 28, 2021 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



e.key === "Shift" don't update the variable
If appropriate, you’d probably also want to screen out Caps Lock ... and let’s not even think about Option/Alt.

csdude55

6:47 pm on Nov 29, 2021 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



@NickMNS, you were right, it WAS that simple :-) I could just ignore the Shift press, and then the next e.key still showed up as D. So no need to worry about the Caps Lock, either.

I'm really replying for future readers, though, to point out that I still had to change it to "keydown" instead of "keyup". I discovered that typing fast would result in e.key returning 0 instead of ), because I was letting off of the Shift key a fraction of a second faster than it expected. Using "keydown" solved that.