In this blog I will show you how you may trigger functionality in your Lightning Web and Aura Component using Keyboard Keys.
To utilize key events you just need to add a event listener for them. In below example I have triggered a button's click on the enter key press event.
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | <template> <lightning-card title="Trigger Button on Enter"> <div class="slds-box"> <lightning-layout multiple-rows> <lightning-layout-item size="12" padding="around-small"> <lightning-input data-id="txt" label="Your text here" type="text" onchange={handleChange} value={txtValue} class="slds-p-top_medium" ></lightning-input> </lightning-layout-item> <lightning-layout-item size="12" padding="around-small"> <lightning-button label="Click me or hit Enter" title="Click me" onclick={handleButton} ></lightning-button> </lightning-layout-item> <template if:true={showValue}> <lightning-layout-item size="12" padding="around-small"> <p style="font-size: xx-large; color: tan"> <b>{txtValue}</b> </p> </lightning-layout-item> </template> </lightning-layout> </div> </lightning-card> </template> |
JS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import { LightningElement } from "lwc"; export default class TriggerButtonOnEnter extends LightningElement { txtValue; showValue = false; renderedCallback() { this.template .querySelector("lightning-input") .addEventListener("keydown", (event) => { // alert("Key: " + event.key + ", Code: " + event.code); if (event.key === "Enter") { this.handleButton(); } }); } handleChange(event) { this.txtValue = event.target.value; } handleButton() { this.showValue = true; } } |
Output
Checkout complete video functionality below
If you have any question please leave a comment below.
If you would like to add something to this post please leave a comment below.
Share this blog with your friends if you find it helpful somehow !
Thanks
Happy Coding :)
0 Comments