I have created a simple code to handle keypress
event:
var counter = 0; $('input').on('keypress', function () { $('div').text('key pressed ' + ++counter); });
JSFiddle.
But keypress event handler is not raised on mobile browser (Android 4+, WindowsPhone 7.5+). What could be the issue?
It works on computers, but not on mobile..
The change event occurs if the value has been changed when the element loses focus. The keypress event occurs every time you press down and release a (non control) key.
KeyboardEvent objects describe a user interaction with the keyboard; each event describes a single interaction between the user and a key (or combination of a key with modifier keys) on the keyboard. The event type ( keydown , keypress , or keyup ) identifies what kind of keyboard activity occurred.
The keypress event is fired when a key that produces a character value is pressed down. Examples of keys that produce a character value are alphabetic, numeric, and punctuation keys. Examples of keys that don't produce a character value are modifier keys such as Alt , Shift , Ctrl , or Meta .
I believe keypress is deprecated now. You can check in the Dom Level 3 Spec. Using keydown or keyup should work. The spec also recommends that you should use beforeinput instead of keypress but I'm not sure what the support of this is.
Use the keyup
event:
// JavaScript: var counter = 0; document.querySelector('input').addEventListener('keyup', function () { document.querySelector('div').textContent = `key up ${++counter}`; }); // jQuery: var counter = 0; $('input').on('keyup', function () { $('div').text('key up ' + ++counter); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With