I would like to set up a home page where pressing any character (lowercase or uppercase) or any number redirects the user to the login page
, as the home page itself doesn't have anything to do that requires typing.
My first attempt was this:
document.onkeyup = function() {
document.location.href = "/login"
}
This works but it works for every key, including cursors, tab, and even caps lock. How can I restrict this function so it only responds to characters and numbers?
I would like to set up a home page where pressing any character (lowercase or uppercase) or any number redirects the user to the login page
, as the home page itself doesn't have anything to do that requires typing.
My first attempt was this:
document.onkeyup = function() {
document.location.href = "/login"
}
This works but it works for every key, including cursors, tab, and even caps lock. How can I restrict this function so it only responds to characters and numbers?
Share Improve this question asked May 24, 2011 at 21:09 sscirrussscirrus 56.8k42 gold badges137 silver badges237 bronze badges3 Answers
Reset to default 5When the event occurs, the key code is sent as an event argument. We can use that to determine if a character or number key was pressed. Like this:
document.onkeyup = function(e) {
if ((e.keyCode >= 65 && e.keyCode <= 90) ||
(e.keyCode >= 97 && e.keyCode <= 122) ||
(e.keyCode >= 48 && e.keyCode <= 57)){
document.location.href = "/login";
}
};
For reference, the number used above are ASCII codes, you can find the plete list here: http://asciitable./. 48-57 are numbers 0-9, 65-90 are upper case characters, and 97-122 are lower case characters.
You can find a very simple JS Fiddle example here: http://jsfiddle/jpYyg/ . Remember to click inside the "Result" panel (bottom-right one) before pressing any buttons or it won't work!
HTH
<script type="text/javascript">
document.onkeyup = function (e) {
var patt =/\w/g;
var key = String.fromCharCode(e.keyCode);
if (patt.test(key))
document.location.href = "/login";
}
</script>
document.onkeyup = function(event) {
if (###event.keyCode corresponds to a letter or numeral###)
document.location.href = "/login";
else
event.preventDefault();
}
You can also see the demo for http://api.jquery./keypress/ if you wish to simplify your life with jQuery.