TAB
can be detected on keydown
event.
By using evt.preventDefault();
you can stop the default behaviour.
DETAILED EXPLANATION:
keydown: will get the code exactly the moment you begin pressing key.
keypress: Will give you Ascii code for all the characters which are printable in screen. This event is generated the moment of press (after key down). examples are all numbers, alphabets, symbols etc.
keyup: This event is the last one in key event sequence (after keypress).
IMPORTANT CONSIDERATIONS:
TAB
can be captured only by keydown
because by the time keyup
event occurs, the focus would have shifted to some other element. So TAB
can be captured only by keydown
.
keypress
should be used to get exact printable character. keydown
and keypress
will not give accurate key code. For example, if you want to know whether symbol %
(percent) is entered, 1st you need press shift and then press 5. Below is the events you get:
Keydown => 16 // when shift
is pressed.
Keydown => 53
// when 5
is pressed (53 code represents 5)
keypress => 37
// when 5
is pressed (37 represents %
) - CORRECT
Keyup =>
53 // when 5
is released
Keyup => 16 // when
shift
is released
As you can see above, only keypress
gave accurate code.
Other non-printable events like control
, shift
, alt
, esc
, enter
etc can be handled by either keydown
or keyup
only. Preferably keyup
.
CAPS
behaves similar to TAB
. When CAPS is switched ON, keydown is fired and when CAPS is switched OFF, keyup is fired.
So, depending on the use case, keydown, keypress or keyup should be used.
TESTING:
<aura:attribute name="sample" type="String" default="" />
<span onkeypress="{!c.handleKeypress}"
onkeyup="{!c.handleKeyup}"
onkeydown="{!c.handleKeydown}"
class="slds-size_11-of-12">
<lightning:inputRichText value="{!v.sample}" label="sample" labelVisible="false"/>
</span>
JS:
({
handleKeypress : function(component, event, helper){
console.log("keypress => ", event.keyCode);
},
handleKeyup : function(component, event, helper){
console.log("handle Keyup => ", event.keyCode);
},
handleKeydown : function(component, event, helper){
console.log("handle Keydown => ", event.keyCode);
}
})