Þaw
Þaw

Reputation: 2057

How to create a tooltip that popups from a focused textbox whenever the Caps Lock key is on?

I have a web-based login form, and I want to notify the user if their Caps Lock key is on, especially when they're typing their password. How can I do this?

Something like: User types username, then focuses on password then if caps lock key is on, a tooltip or popup shows telling the user that caps key is on

Upvotes: 2

Views: 2351

Answers (4)

CodeArtist
CodeArtist

Reputation: 5684

Along with JQuery you will need to add Twitter's Bootstrap in order to enable some effects. Here is your working code.

html

<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/js/bootstrap.min.js"></script>

<input type="password" id="myPasswordField" name="myPasswordField" data-content="Caps Lock is on!"></input>

Javascript

$('#myPasswordField').keypress(function (e) {
    var s = String.fromCharCode(e.which);
    if (s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey) {
        $this = $(this);
        $this.popover('show').click(function (e) {
            $this.popover('hide');
            e.preventDefault();
        });

    }
});

Upvotes: 0

RobG
RobG

Reputation: 147413

There is no current standard for key events and there doesn't appear to be an event property indicating the state of the caps lock key, though it might be provided in future.

The only reasonably reliable way to test for caps lock seems to be to see if the key code is a capital letter and the shift key is not pressed, e.g.

function capsLockOn(e) {
  var code = e.keyCode || w.which;

  if (code >64 && code < 97 && !e.shiftKey) {
    return true;
  }
  return false;
}

On some keyboards, the caps lock only affects keys a to z so you can't reliably test others. Pressing the caps lock key doesn't initiate a key event and would not work reliably anyway since the caps lock might be on before there's a chance to initiate an event.

Or if brevity is your thing:

function capsLockOn(e) {
  var code = e.keyCode || w.which;
  return code > 64 && code < 97 && !e.shiftKey || void 0;
}

Upvotes: 0

Alberto Fecchi
Alberto Fecchi

Reputation: 3396

try this plugin, you can monitor the caps lock state in a textbox or DIRECTLY in the entire window: https://github.com/nosilleg/capslockstate-jquery-plugin

Upvotes: 1

ricardohdz
ricardohdz

Reputation: 579

You can do the following with jQuery

var CAPS_LOCK = 17; //Constant for caps lock key value

$('#myPasswordField').keypress(function(e) { 
    var keyCode = e.keyCode ? e.keyCode : e.which;
    if ( keyCode === CAPS_LOCK ) {
        alert('Caps lock pressed');
    }
});

For more info on key values: For key values see http://help.adobe.com/en_US/AS2LCR/Flash_10.0/help.html?content=00000520.html

Upvotes: 0

Related Questions