I'm attempting to replicate a mouse hover effect using JavaScript. Here is the code I have:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
#chart:hover {
background-color: yellow;
}
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="chart" onmousemove="showCoords(event)">This is a div</div>
<button>Button</button>
<script>
$("button").click(function(){
triggerMouseHover();
});
var triggerMouseHover = function(){
//x, y is coordinate of mouse pointer
function simulateMouseHover(x, y) {
var el = document.elementFromPoint(x, y);
var fireMouseEvent = function (type, x, y) {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent(type, true, true, window, 1, 0, 0, x, y, false, false, false, false, 0, null);
el.dispatchEvent(evt);
};
fireMouseEvent('mousemove', x, y);
fireMouseEvent('mouseleave', x, y);
};
simulateMouseHover(Math.floor((Math.random() * 1260) + 1), (Math.floor(Math.random() * 263) + 1));
}
function showCoords(event) {
console.log ("X: " + event.clientX + " Y: " + event.clientY);
}
</script>
</body>
</html>
I expect the div element to change its background color as if a real mouse hover event is triggered at the specified coordinates (x, y), but the output only shows the mouse move to (x,y) coordinates, not the hover effect. Any help to resolve this issue would be greatly appreciated. Thank you.