work around browsers' inconsistent handling of control keys?

B

Ben Crowell

I have a js application that emulates a terminal:
http://www.lightandmatter.com/calc/inf/
That is, the user types a line of text, hits enter, and gets
a response printed out. Then he can type more text, etc.

Because I have emacs keybindings programmed into my muscle
memory, I would like to make control-P and control-N work
the way they do in emacs and in the bash shell, i.e.,
they allow you to recall previously typed commands and
move up and down through your history of commands. Since
most browsers define control-P, for example, as a print
command, I have to catch those keypress events if they
occur within the text input area, and make sure they don't
bubble up to the browser, by returning false from my event
handler. (You could argue that this is evil, and I shouldn't
mess up the keybindings that the user is used to, but personally
I see this as making the user experience *more* consistent for
me :) I've got this working in firefox and galeon, but not in
konqueror, which still pops up a print dialog when I hit control-P.
Can anyone suggest how to make this work in more browsers? My
code is below.

Thanks in advance!

-Ben

--------------------------------------------------------------------

inp.onkeypress = function(e) {

var code = 0;

if (!e) { // IE
e = window.event;
}
// IE has keyCode, Firefox has charCode
try { code = e.charCode; } catch (foo) {}
try { code = e.keyCode; } catch (foo) {}
if (code==0) {try { code = e.which; } catch (foo) {}}
// necessary for ctl keys in FF
var enter = 13; // unicode for enter key
var up_arrow = 38;
var down_arrow = 40;
var ch = String.fromCharCode(code);
var go_up = (e.ctrlKey && ch=='p') || (code==up_arrow);
var go_down = (e.ctrlKey && ch=='n') || (code==down_arrow);
...
return (!(code==enter || go_up || go_down));
// in these three cases, prevent the browser from doing
// other things, e.g., printing if we do control-p
};
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top