birdus
birdus

Reputation: 7504

Event/object in JavaScript function

If I have some HTML like this:

<a onmouseover='SetTopLeft(this);'href='#'>Click me!</a>

Can I get both the object AND the event in the function? So, for example, can I have a method signature like this?

function SetTopLeft(e, o)

...where e is the event and o is 'this'? I may actually not need the object, but I think I probably DO need the event. I wouldn't mind understanding a little better how this works in JavaScript - i.e., when/how can I pass an event and when/how can I pass the calling object? Can I choose which to pass? Can I pass both?

Basically, what I really need to do is get the mouse coordinates within the DIV within which the anchor is located (even if that DIV is only a portion of a web page and whether or not the browser is full-screen) and I'm having a terrible time getting it done. Most of the examples I have seen for getting these coordinates within some element use the event and the pageX and pageY properties of that event.

By the way, this must work in IE 6 onward. Firefox would be good, too. Others are not necessary.

Upvotes: 2

Views: 1775

Answers (2)

Felix Kling
Felix Kling

Reputation: 816384

In general you should avoid using inline event handlers. It mixes representation (HTML) with logic (JavaScript). quirksmode.org offers a nice collection of articles of all there is to know about event handling.

Since inside an event handler, this typically refers to element the handler is bound to, you can also explicitly set this to the element and pass the event object as first argument:

<a onmouseover='SetTopLeft.call(this, event);'href='#'>Click me!</a>

See .call() [MDN] for more information.

Besides that, if your link is not linking to anything, better use a simple span element or a button and style it accordingly.

Upvotes: 3

Matt Coughlin
Matt Coughlin

Reputation: 18906

Yes, in the inline code this refers to the HTML DOM object for the element, and event refers to the event object. So you could do the following:

HTML

<a onmouseover='SetTopLeft(event, this);' href='#'>Click me!</a>

JavaScript

function SetTopLeft(e, obj) {...}

Upvotes: 4

Related Questions