How to mimic a mouse hover effect with JavaScript

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.

Answer №1

<table style="width:300px;height:100px">
  <tr>
    <td onmouseover="changeColor(this.style.backgroundColor)" 
        onmouseout="changeColor('transparent')"
        style="background-color:LightBlue">
    </td>
    <td onmouseover="changeColor(this.style.backgroundColor)" 
        onmouseout="changeColor('transparent')"
        style="background-color:LightPink">
    </td>
    <td onmouseover="changeColor(this.style.backgroundColor)" 
        onmouseout="changeColor('transparent')"
        style="background-color:LightCoral">
    </td>
  </tr>
</table>

Perhaps this will be effective.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Securing Credit Card Numbers with Masked Input in Ionic 3

After testing out 3-4 npm modules, I encountered issues with each one when trying to mask my ion-input for Credit Card numbers into groups of 4. Every module had its own errors that prevented me from achieving the desired masking result. I am looking for ...

The hamburger menu for mobile devices is not functioning properly on the website's mobile version, however it operates correctly when the screen is resized

Currently, I am facing an issue with the hamburger menu not responding on my mobile device. Oddly enough, it does work when I resize my browser window to mimic a mobile size. There seems to be a glitch happening, but I'm struggling to pinpoint the exa ...

Creating CSS for a specific class on a single webpage can be achieved by targeting that class

Here is my custom style: <style> ul { padding:0 0 0 0; margin:0 0 0 0; } ul li { list-style:none; margin-bottom:25px; } ul li img { cursor: poin ...

Issue: Module '/Users/MYNAME/Desktop/Projects/MYPROJECTNAME' not found

I am currently in the process of compiling Node using TypeScript, and I'm still getting acquainted with it. An issue I encountered was that my /src files were not being updated when I made changes and restarted the server. To troubleshoot, I decided ...

What is the process by which Elastic Beanstalk executes Node.js application code?

While my application runs smoothly on localhost, encountering no issues, deploying it to other platforms such as AWS or MCS presents a challenge. Specifically, the problem lies in recognizing the file paths required by the consign library to load the route ...

Experience the convenience of uploading photos using jQuery Dialog on your ASP.NET MVC website

I am in the process of developing an ASP.NET MVC 3 application and encountering an issue with using a jQuery Dialog to upload a photo. Despite my code implementation, the HttpPostedFileBase object within my model (representing the file to be uploaded) cons ...

The efficiency of Ajax JSON timeouts needs improvement

Currently, I'm in the process of developing an interactive map with specific functionalities. Essentially, the user will click on a year (stored as var currentyear) and then select a country (its name stored as var thenameonly). Subsequently, an AJAX ...

Javascript increasing the variable

Whenever I interact with the code below, it initially displays locationsgohere as empty. However, upon a second click, the data appears as expected. For example, if I input London, UK in the textarea with the ID #id, the corresponding output should be var ...

What could be causing my Ionic/Firebase subscription to be triggered three times?

I'm having an issue with my code where it seems to be executed 3 times and I can't figure out why. advertenciaMantto() { this.afs.doc('Core/Programador').valueChanges().subscribe(async (data) => { await this.afs.firestore.doc(` ...

Manage how child components are displayed in React in a dynamic manner

My React parent component contains child components that are rendered within it. <div id="parent"> {<div style={{ visibility: isComp1 ? "visible" : "hidden" }}><MyComponent1 {...props}/></div>} ...

The performance of Jquery Animate is acting strangely after the upgrade to version 1.11

Take a look at http://jsfiddle.net/integerz/k19x8L1b/2/ which uses version 1.7.x $(function () { $("#clickme").toggle(function () { $(this).parent().animate({right:'0px'}); }, function () { $(this).parent().animate({righ ...

Getting a Node Express 404 error while attempting to display an image that was uploaded using multer

I am facing an issue with uploading images using multer. Previously, everything was working perfectly fine on localhost. The images were getting uploaded and I could view them using the provided URL link in the code. However, after uploading it to a server ...

Attempting to navigate a tutorial on discord.js, I encountered an issue labeled as "Unknown application" that disrupted my progress

I attempted a tutorial for discord.js, but encountered an error message saying "DiscordAPIError[10002]: Unknown Application." Even though I checked my clientID and applicationID and they seem to be correct! You can find the tutorial here. Here is the co ...

Executing all middleware within an express route

Currently, I am in the process of constructing an API using express and have implemented multiple middleware functions in my routes. One of the endpoints I am working on is displayed below: Router.route('/:id/documents') .get([isAuthenticated, ...

Combine the entities within the object

I need to combine two objects that contain other objects within them, similar to the following structure: let selections = { 123: { abc: {name: 'abc'}, def: {name: 'def'} }, 456: { ghi: {name: ' ...

Change the background color of the top element box when scrolling

The code I have implemented reflects my intentions. html: <div id="one" class="box"></div> <div id="two" class="box"></div> <div id="thr" class="box"></div> <div id="fou" class="box"></div> <div id="fiv" ...

activate a single on.click event to trigger additional actions - utilizing javascript and jQuery

My website features dynamically generated buttons that lead to specific pages. The challenge I'm facing is retrieving the automatically generated data-num value for each button and using it as a jQuery selector to redirect users to the corresponding p ...

TypeScript is unaware that a component receives a necessary prop from a Higher Order Component (HOC)

My component export is wrapped with a higher-order component (HOC) that adds a required prop to it, but TypeScript seems unaware that this prop has already been added by the HOC. Here's the Component: import * as React from "react"; import { withTex ...

An onClick event is triggered only after being clicked twice

It seems that the onClick event is not firing on the first click, but only works when clicked twice. The action this.props.PostLike(id) gets triggered with a delay of one click. How can I ensure it works correctly with just one click? The heart state togg ...

Asynchronous Node operations with Promise.all

When working on a basic JS program, I encountered the need for asyncOperation2 and asyncOperation3 to run in sequence with asyncOperation1. The specific order of execution required is either 1,2,3 or 2,3,1. Additionally, after completing these operations, ...