Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function name(e) in Javascript

As a complete Javascript novice I'm challenged by some simple concentps.

When I'm doing my javascript I'll often see stuff like this

function name(e) {

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

What does doing this accomplish? What's the e all about?

like image 206
Johnny Avatar asked Aug 03 '10 15:08

Johnny


3 Answers

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.

like image 76
Mario Avatar answered Sep 30 '22 12:09

Mario


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.

like image 45
fearofawhackplanet Avatar answered Sep 30 '22 13:09

fearofawhackplanet


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) {
like image 35
Nick Craver Avatar answered Sep 30 '22 13:09

Nick Craver