Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 820
Alkis Mavridis Avatar asked Mar 07 '23 10:03

Alkis Mavridis


1 Answers

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.

like image 171
CertainPerformance Avatar answered Mar 12 '23 02:03

CertainPerformance