$('#test').on('input', function(e){
console.log('test');
});
$('#test').on('keydown', function(e){
console.log('test');
});
JavaScript events
This is when the different event are triggered:
change
This will be called when theblur
event is triggered if the value of thehas been changed. In other words it will trigger when the input loses focus the value is different to what it was.
input
Theinput
event is basically everything you are looking for, it captures the event on any input change and most likely came about due to the headaches causes when developing something that watches every keystroke. The input event even manages to catch the case where the mouse pastes in content.Unfortunately theinput
event is relatively new and only available to modern browsers (IE9+).keydown
Thekeydown
event is pretty simple, it triggers when the user pushes the key down..keypress
Thekeypress
event is supposed to represent a character being typed. Because of this is does not capture backspace or delete which immediately dismisses it for use overkeydown
.keyup
Much likekeydown
, it triggers whenever the user releases a key.paste
This handy event triggers when data is pasted into the element.
Modifier keys
Note that
keydown
, keypress
and keyup
carr with them information about the modifier keys ctrl shift and alt in the properties ctrlKey
, shiftKey
and altKey
respectively.The cases
Here is a list of the cases you need to consider:
- Entering input with keyboard (includes holding down a key)Triggers:
keydown
,keypress
,input
,keyup
- Deleting input (backspace/delete)Triggers:
keydown
,input
,keyup
- Pasting using ctrl+vTriggers:
keydown
,paste
,input
,keyup
- Using mouse to pasteTriggers:
paste
,input
- Select an item from the autocomplete (↑/↓)Triggers:
keydown
,keyup
Implementation
Given the above, you could implement your autocomplete box handling the
input
event for all changes to the input, and then keydown
event to handling up and down. This would really separate everything nicely and lead to some pretty clean code.If you want to support IE8, you will need to throw everything except pasting into the
keydown
event and then handle paste
. The paste
event is quite widely supported now and has been in IE since v5.5).Reference:
http://stackoverflow.com/questions/15727324/for-a-javascript-autocomplete-search-box-must-we-use-the-input-event-handler
No comments:
Post a Comment