views:

40

answers:

3

I'm somewhat curious about the "best practices" when it comes to trapping the ENTER key in an html input tag. In IE, it's easy. window.event.keyCode will be 13 when enter is pressed and it's pretty straight forward. In all other browsers, an arguments object is passed into the function. However, this seems to basically force you to late-bind a function handler to the object. You can do:

myInput.onkeypress = function (args)
{
   window.alert(args.keyCode);
};

However, if you wanted to do:

<input onkeypress="checkEnter()" />

Then basically checkEnter() would be called by an anonymous function (which in theory would have the argument object) which would then call checkEnter with no parameters. I guess you could do something totally wacky like:

<input onkeypress="checkEnter(arguments)" />

I haven't tried this but I assume it could work. It seems that this design basically says late-binding is the only reasonable approach for trapping key presses. I'm not a fan of IE in any way, but it seems to me IE got this one right and their design is superior.

Am I missing something?

+1  A: 

As a general rule, you shouldn't ever be specifying JavaScript functions in HTML tags anyway. Let JavaScript code define what JavaScript needs to do, and let the HTML be completely unaware of JavaScript's existence.

In the case of event handlers, that does indeed mean binding functions within the script, rather than in HTML tag parameters.

VoteyDisciple
Yea that's pretty much what I figured.. It's just sometimes I have server-side HTML generated tags with like 50 checkboxes and I want each of them to have an online handler. Late-binding the handlers means a for loop to attach each one.. FYI, I've used jQuery and like it, and I also like Yahoo!'s YUI library quite a bit too.. Both make this stuff easier. Thanks for your reply.
Mike
A: 

The best practice is using what you call late-binding. Also, you should use addEventListener instead of onkeypress, at least in theory.

Another way would be to bind events using some library, like jQuery.

Mewp
and attachEvent in IE…
Marcel Korpel
A: 

Check out how to do it with jQuery.

Another great feature of javascript/jQuery is that you can make it unobtrusive, so you can completely separate your scripts from your html making both more readable and the javascript be cacheable by the browser.

Grz, Kris.

XIII
About unobtrusive JavaScript: that's not a feature of jQuery, you can do this using native JavaScript as well.
Marcel Korpel
Yeah, I know. Hmm, after reading that sentence again it appears indeed that it's only a feature of jQuery. Not the intent of stating it that way that it can be interpreted as such.
XIII