Art F
Art F

Reputation: 4202

Event object in Javascript, trouble finding information

I believe there is an object in javascript called event, I see it in some code that wasn't written by me in lines that look something like this:

event.x + document.body.scrollLeft;

I am having trouble finding more out information, furthermore, the object comes up undefined in Firefox. It works fine in all the other browsers. Can anyone provide me with more information? Specifically how do I access this object in Firefox?

Upvotes: 2

Views: 62

Answers (2)

Noah Freitas
Noah Freitas

Reputation: 17430

event (or just e) is a common first parameter name for event handler functions.

In all modern browsers except IE a function registered as an event handler will be passed an Event object as its first parameter containing information about the event.

In IE similar information is available in the global event object (window.event).

Because of these browser differences you will often see event handler boilerplate code such as:

var clicked = function (e) {
  e = e || window.event;  // sets e to window.event if no parameter was passed
};

Upvotes: 0

Jeff Noel
Jeff Noel

Reputation: 7618

Official W3c reccomendation

clientX and clientY are the official event property handlers you are looking for. Although you might want to consider screenX and screenY too.


Events (API)

Events

Creating, triggering events

Event handlers

Orientation and motion data


Window Event X and Y property

Explanation

event.x and event.y, what are those?

First of all, the x and y properties are not in all events. It is relative on the event triggered.

Here is an example:

document.body.onclick = function(){console.log(window.event.x)};

If you paste and execute that code in your browser's console, it will log you the x position of the cursor each time you click.


Although taking a look at this example:

document.body.onkeyup = function(){console.log(window.event.x)};

The console will log undefined each and everytime you release a key from your keyboard, since the onkeyup() event does not hold any values for the x and y properties.

Upvotes: 2

Related Questions