user978122
user978122

Reputation: 5761

Getting the HTML tags under a mouse cursor

Would anyone happen to know how to get the HTML tag directly under a mouse cursor on a web page? I am working on a new type of WYSIWYG, and wish to implement some true drag and drop capabilities (not insert at cursor, which is so common to WYSIWYGs these days); to do that, I need to know where to insert a menu item when a mousebutton up event fires.

Ideas are welcome as well, as I understand it may be a complicated problem.

Upvotes: 2

Views: 2898

Answers (2)

Mikey
Mikey

Reputation: 2951

Here's an example based upon the link @mightyuhu suggested:

document.onmouseover = function(e){
    targ = getTarget(e);
    targ.style.border = '1px solid #F00';
    document.getElementById('currentElement').innerHTML = targ.tagName;
};

document.onmouseout = function(e){
    getTarget(e).style.border = 'none';
};


function getTarget(e){
    if (e.target) return e.target;
    else if (e.srcElement) return e.srcElement;
}

There's also this: http://jsfiddle.net/5NFeX/3/

Upvotes: 3

aefxx
aefxx

Reputation: 25249

Actually, it's not that complicated. You would have to bind your event handler to the document itself, then examine the original target the event got fired off. See mightyuhu's comment for an example.

One suggestion at last: Use one of the major JavaScript frameworks to ease the pain of writing cross-browser event handling code.

Upvotes: 2

Related Questions