views:

247

answers:

4

Hi,

I am a beginner to Javascript. And when I was practicing I have noticed something.

Take this function:

<script type="text/javascript">
    function showChar(sSomeData, oEvent)
    {
     alert (oEvent.keyCode);
     return true;
    }

</script>

When I call this function as this:

 <input type="text" id="txtTextBox" onkeypress="return showChar('some text', oEvent);" />

I get a JS error: "Microsoft JScript runtime error: 'oEvent' is undefined"

But if I rename oEvent with 'event' like:

<input type="text" id="txtTextBox" onkeypress="return showChar('some text', event);" />

Then it works fine. My conclusion is 'event'is a reserved word which stands for event argument in Java Script. But when I have checked the net I did not see 'event' as a reserved word.

Am I mistaken or it is not really documented as a reserved word?

Thanks!

+8  A: 

It is not a reserved keyword, but it is a global variable in IE at least.

Locksfree
Then for other browser what should I use as a variable name that can stand for event argument in this case?
burak ozdogan
Your problem is not the name, it the way event attributes work. See Ionut's answer below (Which should be voted up).
Marco
That `event` variable it's actually an argument which is shadowing the global `event` variable in IE. That's why it work in **both** IE and FF.
Ionuț G. Stan
+4  A: 

List of javascript reserved words

Steerpike
+6  A: 

Well, the code:

onkeypress="return showChar('some text', oEvent);"

Is the equivalent of the following JavaScript code:

element.onkeypress = function (eventObjectName) {
    return showChar('some text', eventObjectName);
};

Is just that browser name the event argument as event.

So, the value of the attribute is wrapped in a JS function which receives an argument named event which is the event object.

Ionuț G. Stan
The equivalent would be `element.onkeypress = function (e) { return showChar('some text', oEvent); };` or (for IE) `element.onkeypress = function () { return showChar('some text', oEvent); };`
outis
@outis, but `oEvent` would be `undefined` in your example.
Ionuț G. Stan
+2  A: 

No, event is not a reserved word. It is, however, a variable which is set by all the major browsers when an event handler (such as onkeypress) of a DOM node is being executed. In IE, it is also a global variable.

A typical cross-browser way to get the event is along these lines.

On the DOM node:

<div onclick='someFunction(event)'>Click me</div>

The event handling function:

function someFunction(evt) {
  var srcElem = evt.srcElement || evt.target;

  // Code continues
}

By the way, in your example, oEvent is the name of the parameter and is therefore valid in the context of the function being called, not in the context of the caller.

jhurshman