views:

84

answers:

7

As a complete Javascript novice I'm challenged by what may seem like simple concepts to the almighty javascript overlords that call Stackoverflow home.

My problem isn't really problem. When I'm doing my javascript up in my code editor down at the ghetto I'll often see stuff like this

function name(e) {

    if(e.KeyCode) { 
        ....
    }
}

What does doing this accomplish? How is this different from just doing if(KeyCode)? What's the e all about?

Thanks :)

+2  A: 

e here is the event. Note that the letter e isn't important, it's just a paramater name. You could call it anything, but e is standard and makes it obvious to other people reading your code.

example:

<input type="text" onkeyup="doSomething(event)"/>

function doSomething(e) {
    alert('you pressed key:' + e.keyCode);
}

So e.keyCode is telling you which key was pressed.

fearofawhackplanet
`keyCode`, not `KeyCode`.
Tim Down
oops thanks Tim. I just copied it from the OP. Corrected now :)
fearofawhackplanet
+1  A: 

The e is the event object passed to the function in most cases, it's checking the keyCode property of the event object that was passed in.

For example in Firefox you can do this:

document.onclick = myFunction;
function myFunction(e) {
  //e is the click event object
  //e.keyCode, e.target, etc.
}

This works because by default, it passes the event to the handler as the first argument. For your example does this make it clearer?

function name(someObject) { //or event, or any name works
  if(someObject.keyCode) {
Nick Craver
You'll need the nasty `e = e || window.event` thing here for IE.
Tim Down
+1  A: 

"e" is a parameter - an event object - passed to the function when it's called.

DVK
+3  A: 

Seems like the function is to be called by the browser (or whatever) when firing a specific event (in this case I guess it's keyboard related; e stands for event or event data).

So once fired, the caller will pass the event structure as a parameter (copied to e). JavaScript won't define any local/global variables just for the one specific call so KeyCode won't be defined but e contains that variable.

Mario
A: 

It is an event object. Read about Events.

Felix Kling
+1  A: 

KeyCode is undefined (by itself). It is a property or attribute of e, so you must call it with e.KeyCode. e is (presumably) an event object. Maybe you should brush up on OOP?

Mark
`keyCode`, not `KeyCode`.
Tim Down
@Tim: Just wrote it the way he had it. C# conventions start with a cap letter... forgot what JS does.
Mark
+1  A: 

e = shorthand variable name for the event that gets passed into the function.

DA