In javascript I'd like to be able to determine the element in the html page in which a mouse click occurs. Note that the elements will not have an event listener attached.
Basically: cursor somewhere in page, user clicks mouse, capture mouse click event, get element in which click occurred. Is this possible?
One approach I thought of is to get the x,y coords of the click event, iterate through the DOM getting the positions for each element, and finding the inner-most element which contains the click event. Sounds a bit long-winded though - so was wondering if there was another way.
http://www.quirksmode.org is a very nice website that explains a lot about events.
Especially for your question: Event properties - Which HTML element is the target of the event?.
In Internet Explorer, you can get the element from the event
object with event.srcElement
[docs] and in all other browsers with event.target
[docs].
Also see the "Safari bug" workaround in the example I linked to (although I don't know whether it still exist and/or in what version of Safari).
Try event.target. There is an example on that page which shows how to use it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With