Related Posts

Archive

Capturing keys with Javascript

February 16th, 2006

So in creating a chat interface, there were a few undesired browser features to overcome - protecting people who actually know how to use their keyboards on a form: The Enter (return) key, the Backspace key, and the Tab key.

Now almost every key on the keyboard has a code assigned to it. The actual keys vary - like I have found no way to control the tab key via javascript in firefox - which would be a real chang in the browsers’ behavior, so it is understandable. For the other two, I have code.

var texting=false;
window.onload = function() {
document.getElementById("sendable").onfocus = function() { texting=true; }
document.getElementById("sendable").onblur = function() { texting=false;}
document.getElementById("sendable").focus();
document.onkeypress = enterSubmit;
if(!document.onkeypress) document.onkeydown = enterSubmit;
}
function enterSubmit(e) {
var pK = e ? e.which : window.event.keyCode;
if ( pK != 13 && pK != 8 ) {
//alert(pK);
return pK;
}
else if ( pK == 8 ){
if(!texting){
//alert("backspace Key refocus");
dummy = document.getElementById("sendable");
dummy.focus();
dummy.value = dummy.value.substr(0, dummy.value.length -1);
return false;
}
else return pK;
}
else {
//alert("Enter Key hit");
return false;
}
}

Now, by all my tests, the Enter key has a code of 13, the Backspace key a code of 8. Uncomment the alerts to get more. These are standard ASCII codes, if you want to find a table.

“sendable” is my primary text input - where focus almost always is placed. So if it is selected, things work normally. Otherwise, I can prevent going back in history AND switch back to the input.

This form actually has no submit button, because it is already dependant on javascript - the form should actually never submit in a ‘normal’ way - and the enter key can still do that. So code 13 is disabled by returning a false - of course, I could always put in a call to the right javascript submit function.

onkeypress and onkeydown are for Firefox (and hopefully other ‘good’ browsers) and Internet Explorer respectively.

Posted in JavaScript |

Comments are closed.

Previous post: The 132nd day - Concerns of the Search

Next Post: On the Scale of Multiplicity