I try to simulate mouse hover using javascript Here is my code:
<!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>
My expected output is div element will change background color like really mouse hover event with exactly coordinations (x, y), but output is only mouse move to (x,y), not mouse hover. Please help me to resolve it. Thanks a lot.