views:

995

answers:

6

how can i get the id of a html control just by specifying the coordinates of a triggered event (like onmousedown, onmouseup, onclick, etc..). the coordinates can be got by

e.clientX , e.clientY where e is the event object.

the idea is to get the id of control on which a click event is done without having any onClick event in that control's definition.

this will dispense the need of specifying the onClick event for multiple controls.

+1  A: 

this will dispense the need of specifying the onClick event for multiple controls.

If this is your only goal, I suggest using jQuery to elegantly specify event handlers on multiple elements.

This one of examples from jQuery tutorial that does exactly this:

 $(document).ready(function() {
    $("a[href*=/content/gallery]").click(function() {
       // do something with all links that point somewhere to /content/gallery
    });
 })
Alex Lebedev
+5  A: 

I do not believe that this is possible, but fortunately (if I understand your requirements correctly) you do not need to:

If you want to get the HTML element where a user clicked, without specifying a click event handler on each element, simply specify a click handler on a top level element (one that contains all the other interesting elements - maybe even "document"), and then look at the MouseEvent's target property - it will specify the HTML element that received the click initially and not the element where you specified the onclick event handler (this can be gotten to simply by using the "this" keyword).

If you have firebug, try this out in your firebug console right here on StackOverflow:

document.getElementById('question').onclick = function(e) { 
  var target = window.event?window.event.srcElement:e.target; 
  alert("Got click: " + target); 
}

Then click anywhere on your question text to get an alert with the correct HTML element :-) .

Guss
@Gussiam getting an error: 'Target' is null or not an objectthis is what i am trying to dowritetext(document.getElementById('txt1'),e.clientX +" " + e.clientY+" "+e.Target);the target clicked is - <input type="button" id=btn1 name=btn1 value="hi "/> e.Target.className="td1";
kk
On IE, no ‘e’ argument is passed in; you have to use window.event.srcElement instead. So: “var target= e? e.target : event.srcElement”.
bobince
Indeed. I've edited the answer for the X-browser compatibility. The example was for Firebug which only runs on Firefox - so I thought I was safe :-)
Guss
https://developer.mozilla.org/En/DOM:document.elementFromPoint
Rajat
A: 

When your HTML page renders positions of various elements will be derived dynamically by the rendering engine of your browser. The only elements which can reliably be tested for their resulting layout properties are images.

To do what you want, therefore, you would need to use absolute positioning for all your elements and have a page map stored elsewhere to tie up controls to locations. This would be way too complicated I think!

Although it contradicts your question somewhat, you should, via javascript or server side, attach onclick events to your controls. Sorry!

CodeBadger
A: 

You don't actually need the position. What you need is the target property of the event object. I don't know how this is handled in jQuery but here's a quick example inspired from the above resource:

JavaScript

<script type="text/javascript">
window.onload = function() {
    document.body.onclick = function(event) {
        alert(event.target.id);
    }
}
</script>

CSS

div {
 width: 200px;
 height: 200px;
 margin: 30px;
 background: red;
}

HTML

<div id="first-div"></div>
<div id="second-div"></div>
Ionuț G. Stan
does your code work in ie 6, i have problem in the target object. ie is not recognising it and iam getting an error : target is null or not a valid object
kk
No, it does not work. The solution Guss offered is better.
Ionuț G. Stan
+1  A: 

This is a very good question, lets suppose the function we are looking for is something like this:

document.elementFromPoint = function(x,y) { return element; };

This obscure function is actually implemented in Firefox 3.0 using the gecko layout engine.

https://developer.mozilla.org/en/DOM/document.elementFromPoint

It doesn't work anywhere else though. You could build this function yourself though:

document.elementFromPoint = function(x,y) {

    // Scan through every single HTML element
    var allElements = document.getElementsByTagName("*");

    for( var i = 0, l = allElements.length; i < l; i++ ) {

        // If the element contains the coordinate then we found an element:
        if( getShape(allElements[i]).containsCoord(x,y) ) {
            return allElements[i];
        }

    }

    return document.body;

};

That would be very slow, however, it could potentially work! If you were looking for something like this to make your HTML code faster then find something else instead...

Basically what that does is it goes through every single HTML element there is in the document and tries to find one which contains the coordinate. We can get the shape of an HTML element by using element.offsetTop and element.offsetWidth.

I might find myself using something like this someday. This could be useful if you want to make something universal across the entire document. Like a tooltip system that works anywhere, or a system that launches context menus at any left click. It would be preferable to find some way to cache the results of getShape on the HTML element...

jhuni
A: 

Check this :

http://www.quirksmode.org/dom/tests/elementfrompoint.html

You can also see the MDC reference for the same call.

Rajat