views:

90

answers:

3

Hi,

does anyone know how i can get the id of any element when the mouse is over ?

I want to show a div (box) over the elements (tags) the mouse is over. I cannot modify the tags to include a mousover event. I want a global callback or something like that to have the id of the tag which is under the mouse pointer.

Thanks !

A: 

This might be helpful

Aviatrix
It is a nice piece of code indeed. But the solution offered by Karim79 is more like it.I know you posted this because of my bad description of the problem. (I do want access to the element itself).Thanks for your help.
oimoim
+5  A: 

You mean you want the target of the onmouseover event, so you can access the element's properties:

<script>
document.onmouseover = function(e) {
    console.log(e.target.id);
}
</script>

Take a look at Event Properties for a cross-browser way to get the target (the following example is from the aforementioned website):

function doSomething(e) {
    var targ;
    if (!e) var e = window.event;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;
}

So to put those together:

document.onmouseover = function(e) {
    var targ;
    if (!e) var e = window.event;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;
    console.log(targ.id);
}
karim79
Wow !!! This seems to be it ! console.log is the function i was looking for.Let me try it :)Thanks !!!
oimoim
I mean e.srcElement
oimoim
A: 

May not be what you're looking for. but if you use the web developer tools for firefox, you can select Information -> Display id and class details. This will display the ID and class information of every element on the page. Also using CSS -> View Style Information will allow you to hover over elements and have their class and id hierarchy displayed individually when you hover over them. I only offer this solution because I assume you don't want the functionality available to the user, but rather as a tool to debug the website.

Kibbee
Thanks for your answer Kibbee, but I do want to offer this functionality to the user. The firebug extension does exactly this when inspecting elements but I need to be able to do it without extension.Thanks.
oimoim