Skip to content

Instantly share code, notes, and snippets.

@joostvanveen
Created October 8, 2015 09:03
Show Gist options
  • Save joostvanveen/114225d370bb8a62dd4c to your computer and use it in GitHub Desktop.
Save joostvanveen/114225d370bb8a62dd4c to your computer and use it in GitHub Desktop.
jQuery script that displays a warning if capslock is on. Handy for password inputs.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Capslock check</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<style>
.capslock { color: red; }
</style>
</head>
<body>
Test if capslock is on:
<div class="detectCapslocks" data-message="Your capslock is on">
<input type="text" class="detectCapslocks">
</div>
<script>
$(function() {
/**
* Display a warning on capslock
*/
$('.detectCapslocks input').keypress(function(e) {
// Detect current character & shift key
var character = e.keyCode ? e.keyCode : e.which;
var sftKey = e.shiftKey ? e.shiftKey : ((character == 16) ? true : false);
// Is caps lock on?
isCapsLock = (((character >= 65 && character <= 90) && !sftKey) || ((character >= 97 && character <= 122) && sftKey));
// Display warning and set css
if (isCapsLock == true) {
var parent = $(this).parent();
parent.addClass('capslock');
$('.capslockMessage').remove();
parent.append('<div class="capslockMessage">' + parent.data('message') + '</div>');
}
});
});
</script>
</body>
</html>
@nsbgit
Copy link

nsbgit commented May 24, 2018

Can anyone explain how the code is working inside if block

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment