Event.observe problem

2 views
Skip to first unread message

nxt

unread,
Aug 31, 2006, 9:06:05 AM8/31/06
to Ruby on Rails: Spinoffs
Hi everyone!
I came across and interesting problem with prototype Event.observe.
Take this code for example:

<script type="text/javascript" src="cropper/lib/prototype.js"></script>
<script language="JavaScript"><!--
function handler(e) {
if (document.all) { e = window.event; }
var key;
if (document.layers) key = e.which;
if (document.all) key = e.keyCode
alert('Unicode value of key pressed was ' + e.keyCode);
}
window.onload = function(){ Event.observe($('testselect'), 'keypress',
handler);}
//--></script>
<form>
Inline: <input type="text" onKeyPress="handler()">
Observing: <input id="testselect" />
</form>


Let's say, I press an "s" key. In the first, inline event, it alerts
keyCode 115 =s. Doing the same in the observed input it alerts keyCode
83=S. Somehow the Event.observer capitalizes the character. (and it
gets a bit wild with special characters from numlock etc.)

Does anyone now how to make Event.observer return the correct value?

Ryan Gahl

unread,
Aug 31, 2006, 10:08:05 AM8/31/06
to rubyonrail...@googlegroups.com
This is not an issue with Prototype. This is an issue with the difference in the event model implementation between using inline event handler attachment vs. the W3C event model.

I ran into this same problem a while back... it sucks. Either inline event handler attachment or simply assigning the handler to the "on"X property of the element (without using the more robust W3C attachment methods, which Event.observe does), yields the correct character keys. The W3C model makes you have to do silly things like check whether or not the shift key was also depressed, but that does not account for the fact that you can have the CAPSLOCK key on. It's one of the dumbest things I've come across.

So the following works:


<input type="text" onKeyPress="handler()">
and...
$('testselect').onkeypress = handler;

But the following does not (remember, all Event.observe is doing here is calling the appropriate W3C event handler attachment method on the element, depending on which browser is being used):


Event.observe($('testselect'), "keypress", handler);


And as far as I know you can't do anything about it except use the old methods (inline or direct attachment) wherever you need to know the case of the key that was pressed reliably. Sucks.

nxt

unread,
Sep 1, 2006, 6:04:59 AM9/1/06
to Ruby on Rails: Spinoffs
Got it. Thanks for the info!

Reply all
Reply to author
Forward
0 new messages