Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get html element in which a mouse click occurred?

Tags:

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.

like image 264
Richard H Avatar asked Mar 03 '11 13:03

Richard H


2 Answers

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).

like image 152
Felix Kling Avatar answered Oct 03 '22 21:10

Felix Kling


Try event.target. There is an example on that page which shows how to use it.

like image 28
Douglas Avatar answered Oct 03 '22 21:10

Douglas