PDA

View Full Version : onkeypress as attribute of body tag



ahs10
10-24-2008, 09:52 PM
i'd like to test to see if a user has pressed a key combination like this...



<script type="text/javascritpt">
function key(e) {
if (e.keyCode == 18) {
alert('whatever');
}
}
</script>
<body onkeypress="javascript:key(event);">
blah blah blah
</body>


is this smart though? this page will have many text areas and text fields on it as well. is it too much to ask the browser to evaluate the value of a keystroke each time a key is pressed?

any guidance would be much appreciated. thanks!

magicyte
10-24-2008, 09:59 PM
Well, it is actually good. I would recommend taking the javascript: part out of your event handler. You also need a head tag. This wouldn't mess with the page much, though (if at all, not enough to be bad). Yeah. It's okay.

-magicyte

ahs10
10-24-2008, 10:05 PM
thanks =)

i forgot to put the head tags in :rolleyes:

however, i did not know if was bad to include javascript:

i guess it is kind of redundant, but does it cause issues? i've just gotten in the habit (which might be a bad one) of putting that in front of everything that's referring to js. should i leave it out of all event handlers and javascript delegates?

magicyte
10-24-2008, 10:08 PM
Leave it out of event handlers, but leave them in href="" s. If you want to activate a function or javascript w/in a link, leave the javascript: part. Also, I don't think it would effect it, but do it just in case. Href's are automatically defaulted to URLS. If you use javascript:, it then converts to javascript to call functions. Event handlers are defaulted to client-scripting code.

-magicyte

jscheuer1
10-25-2008, 04:49 AM
onkeydown is more reliable than onkeypress. Also, if you want backward compatibility, check e.which as a fall back:


var key = function (e) {
e = e || window.event;
var k = e.keyCode || e.which;
if (k == 18) {
alert('whatever');
};
};
document.onkeydown = key;

No need for an event attribute in the body tag.

magicyte
10-25-2008, 08:18 PM
Aye. I didn't notice he/she used onkeypress. onkeydown and onkeyup are your standard event handlers for pressing keys.

-magicyte