Reputation: 541
With the help of JavaScript, of course.
Upvotes: 0
Views: 730
Reputation: 25154
In the example below, if you mouse over a div, it will become blue.
If you place the onmouseover to the full BODY, then you can then check on a condition(ID, className, tagName,...) if you want to do something on the element you are overing.
<html>
<head>
<title>so</title>
</head>
<body>
<div>div 1</div>
<div>div 2</div>
<div>div 3</div>
<script>
document.body.onmouseover = function(ev){
var elm = ev.target || ev.srcElement;
if(elm.tagName === 'DIV'){
elm.style.backgroundColor = "#DEF";
}
};
</script>
</body>
</html>
Upvotes: 1
Reputation: 344507
The easiest way is to handle the onmouseover
and onmouseout
event for the elements:
element.onmouseover = function (e)
{
e = e || window.event;
alert("You moused over "+element.outerHTML);
}
element.onmouseout = function (e)
{
e = e || window.event;
alert("You moused out of "+element.outerHTML);
}
You can also use document.elementFromPoint(x, y)
if the element is the topmost element at those co-ordinates:
var mouseX = 0, mouseY = 0;
document.documentElement.onmousemove = function (e)
{
e = e || window.event;
mouseX = e.clientX;
mouseY = e.clientY;
}
function getElementUnderMouse()
{
return document.elementFromPoint(mouseX, mouseY);
}
Obviously if you have certain elements that prevent propagation/bubbling of the onmousemove
event the mouse position could be incorrect whilst hovering over those elements.
Upvotes: 3