Forum Moderators: open
[edited by: MrGecko at 12:14 pm (utc) on Aug. 15, 2007]
But more importantly, your approach is flawed in that the global 'event' object only exists for IE, so this won't work for users of other browsers (Firefox, Opera, Safari).
What you might do instead is use a JavaScript Library like the Yahoo UI (aka YUI) Library to capture the event. The YUI Event Utility is robust and will work across browsers. Below is how you might accomplish your goal with the YUI. Note also the use of unobtrusive JavaScript (instead of using the onKeyPress attribute, attach your script handlers from within your JavaScript... it leaves your markup cleaner and easier to maintain):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset:utf-8">
<title></title>
<script type="text/javascript" src="http://yui.yahooapis.com/2.2.2/build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script type="text/javascript">
function send() {
alert('sending...');
}
YAHOO.util.Event.on(window, 'load', function(e) {
// Attach event handlers
YAHOO.util.Event.on('message', 'keypress', function(e) {
if (YAHOO.util.Event.getCharCode(e) == 13) {
send();
}
});
});
</script>
</head>
<body>
<form action="">
<div>
<input id="message" type="text" size="60" >
</div>
</body>
</html>
Here's a sample script that proves it.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset:utf-8">
<title></title>
<script type="text/javascript">
window.onload = function() {
var foo = document.getElementById('foo');
foo.onclick = function(e) {
alert('e = ' + e); // Works for Firefox
alert('event = ' + event); // Works for IE
}
}
</script>
</head>
<body>
<a href="#" id="foo">Click me</a>
</body>
</html>
Also worth noting that these objects are slightly different. For example, in IE the event has a keyCode and srcElement properties, but in Firefox the equivalent properties are charCode and target. Rather than dealing with all that, the Yahoo Event Utility gives you a nice API and it handles all of the browser specific stuff behind the scenes so you don't need to worry about it.