2

I'm trying to implement something that I would do in plain JavaScript and get it to work in Lightning. I want to detect a keyup action on an input field, so I have my component wrapped within a span like this:

<span onkeyup="{!c.keyCheck}">
    <lightning:input aura:id="pwInput" type="password" label="Password" />
</span>

And my Controller method:

keyCheck : function(event) {       
    // If "caps lock" is pressed, display the warning text
    if (event.getModifierState("CapsLock")) {
        console.log("Caps lock on");
    } else {
        console.log("Caps lock off");
    }
}

This isn't firing. If this were vanilla JavaScript I'd have the EventListener set in the JS like this (which works fine in plain JS):

var input = document.getElementById("pwInput");

input.addEventListener("keyup", function(event) {
    // If "caps lock" is pressed, display the warning text
    if (event.getModifierState("CapsLock")) {
        console.log("Caps lock on");
    } else {
        console.log("Caps lock off");
    }
});

But I thought that's what adding onkeyup="{!c.keyCheck}" in the component was doing. Do you have any suggestions?

3

Controller methods always have three parameters: component, event, helper, in that order. What's confused you is that you've named the first parameter "event". This is actually the component itself. This difference is the main change between vanilla JavaScript and Aura components.

You need to use the second parameter:

keyCheck: function(component, event) {
  if(event.key === 'CapsLock') {
    console.log('Caps Lock pressed');
  } else {
    console.log('Caps Lock was not pressed');
  }
}
|improve this answer|||||
  • i agree with this,but why event.getModifierState() gives error like Uncaught TypeError: Illegal invocation because of locker service? – sdandamud1 Jun 6 '19 at 18:37
  • @sfdcfox - thank you! I appreciate the help. – Matt Smith Jun 6 '19 at 18:42
  • @sdandamud1 - I don't know why that happens. I'm using event.getModifierState in this instance because event.keyCode is deprecated and not recommended now. – Matt Smith Jun 6 '19 at 18:42
  • so you get value for this `event.getModifierState()' ? – sdandamud1 Jun 6 '19 at 18:45
  • @sdandamud1 yes. At least in my scratch org. Hopefully I don't get Locker issues moving it to dev. – Matt Smith Jun 6 '19 at 19:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.