DEV Community


Posted on • Originally published at

jQuery: How to show a warning when CAPSLOCK is on

Alt Text

I've wrote a light-weight jQuery script which allows you to easily show a warning under a field when the CAPS LOCK key is active, the script requires no plugins or require any manual placement of any HTML.

Simply drop the java-script below onto any pages you require the warning and just configure what fields you want it to work on, the script will then do the rest as needed.

I wrote this script because I didn't want to be messing around adding hidden HTML portions under fields or any other modifications, simply wanted to drop my script on a page, point to the input fields of interest and have it do its magic for me.

I realised quickly that I needed the field to hover just below the input fields too so that no HTML on the page is shifted when the warning appears, so this CAPS warning actually floats just below the field being activated on.

It also automatically destroys itself after 5 seconds which you can change if required, and finally if you click the warning that also destroys it from the screen. Handy for when the warning might get in the way of elements etc.

Of course if you dont feel my styling, you're more than welcome to modify the CSS parts of the jQuery to your own liking - change the auto-removal timing or remove as necessary.

//change #password below to either an ID of the field you want
//you could use a class ie. .password or any other jquery selector.
//this works fine with one block on multiple fields, so ie. #password, #password2

//on the setTimeout you can change 5000 to an amount of seconds you want until the warning auto-disappears

$('#password').keypress(function(e) { 
    var s = String.fromCharCode( e.which );

    var pfield = $(this).position();

    //check whether the input is in caps and the shiftkey isnt being pressed
    if ((s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey) ||
       (s.toUpperCase() !== s && s.toLowerCase() === s && e.shiftKey)){
       //check to see if the capsalert is already present
        if ($(this).parent().find('#capsalert').length < 1) {
            //caps alert HTML, edit as necessary
            $(this).after('<b id="capsalert" onclick="$(this).remove();">WARNING: Caps-Lock is on!</b>');
            //the css for the caps alert, modify as necessary
                .css('position', 'absolute')
                .css('top', ( + $(this).outerHeight() + 1) + 'px')
                .css('left', (pfield.left) + 'px')
                .css('border-radius', '5px')
                .css('padding', '5px')
                .css('cursor', 'pointer')
                .css('background-color', '#ffe599')
                .css('border', '1px solid #e6ab00');

            //the timeout for the capsalert
    } else {
        //removes any alerts once it detects no caps lock

Top comments (0)