4

Possible Duplicate:
In Javascript/jQuery what does (e) mean?

I'm new to programming. What exactly is the "e" in function(e) in the code below? I'm guessing it's whatever the recipient of the method is, and what "this" refers to? Just a wild guess. But even so, wouldn't we be able to leave function(e) as function() without the "e"?

$("#" + id).live("mouseenter", function (e) {
    $(this).toggleClass("twittereyesopen");
});
Community
  • 1
  • 1
bigpotato
  • 26,262
  • 56
  • 178
  • 334
  • As a general rule, if you just stick console.log(e) into the function you can use web inspector or firebug or whatever your browser's tools are to find this out in a matter of seconds. – moopet Aug 27 '12 at 16:01

3 Answers3

5

e is an event object, it contains event data. Refer to jQuery Event Type, where you can find description of attributes and methods:

Attributes:

  1. event.type
  2. event.target
  3. event.data
  4. event.relatedTarget
  5. event.currentTarget
  6. event.pageX/Y
  7. event.result
  8. event.timeStamp

Methods:

  1. event.preventDefault()
  2. event.isDefaultPrevented()
  3. event.stopPropagation()
  4. event.isPropagationStopped()
  5. event.stopImmediatePropagation()
  6. event.isImmediatePropagationStopped()
Zbigniew
  • 27,184
  • 6
  • 59
  • 66
3

e is just a parameter name. You can name it however you want to. It will refer to the first argument passed to the function, which in this case will be the event object:

When the browser triggers an event or other JavaScript calls jQuery's .trigger() method, jQuery passes the handler an event object it can use to analyze and change the status of the event. This object includes a normalized subset of data provided by the browser; the browser's unmodified native event object is available in event.originalEvent.

What this refers to depends on how a function is called. In jQuery, this inside event handlers refers to the element the handler is (logically) bound to:

When jQuery calls a handler, the this keyword is a reference to the element where the event is being delivered; for directly bound events this is the element where the event was attached and for delegated events this is an element matching selector. (Note that this may not be equal to event.target if the event has bubbled from a descendant element.) To create a jQuery object from the element so that it can be used with jQuery methods, use $(this).

MDN provides a good explanation of this in general.

You can find more information in the .on documentation.

But even so, wouldn't we be able to leave function(e) as function() without the "e"?

Yes of course, in JavaScript you can define functions without parameters, but passing arguments to them won't throw an error.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
2

The e stands for an event. You are capturing the event, and can perform actions on the event.

Sablefoste
  • 4,032
  • 3
  • 37
  • 58