views:

59

answers:

3

How to get the id of the div on which the mouse is currently pointing?

A: 
<div id="the-id" onmouseover="alert(this.id)">some text</div>
Alberto Zaccagni
@Downvoters: What's wrong with my answer? Not for the two -1 (don't care) but for the way i solved the problem.
Alberto Zaccagni
no vote from me, but you'd have to do that on every element if you want to determine which one you are currently over.
lincolnk
Of course, yes, but the op did not specify he wanted something like that. Btw i've understood, thanks. ;)
Alberto Zaccagni
+7  A: 

I think your best bet is to track mouseover at the document level and maintain the id of the last element hit.

var lastID = null;

var handleMouseover = function (e) {
    var target = e.target || e.srcElement;
    lastID = target.id;
};

if (document.addEventListener) {
    document.addEventListener('mouseover', handleMouseover, false);
}
else {
    document.attachEvent('onmouseover', handleMouseover);
}
lincolnk
+1  A: 

You can use a javascript variable to store the current hovered div.. jQuery (or standard JS) could be used to set the event handler to populate the variable.

Visible test at: http://jsfiddle.net/gfosco/Hys7r/

Fosco
Thats a great answer. Thanks