Alkis Mavridis
Alkis Mavridis

Reputation: 1211

html: Accessing a mouse event from onclick attribute

I know that I can access a mouse event if I assign the mouse listener with js:

myElement.addEventListener("click", e => console.log(e.pageX))

My question is: is it possible to access the mouse event when assigning the listener by html attribute?

<div onclick="alert('where is the mouse event?')"></div>

Upvotes: 4

Views: 1735

Answers (2)

Mamun
Mamun

Reputation: 68943

You can check that by passing event to the function:

function checkEvent(e, msg){
  console.log(e.type, 'event has been fired.');
  console.log(e.pageX);
}
<div onclick="checkEvent(event, 'where is the mouse event?')" >Click My Div</div>

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 370789

The onclick will be evaluated as the inside of a function, and that function will have an argument of the event, so you can do it like this:

<div onclick="console.log(arguments[0].pageX)">text</div>

But you really, really shouldn't. Always attach listeners with Javascript instead of HTML-inline-eval. Code will be easier to write, easier to read, safer, and more maintainable.

Upvotes: 5

Related Questions