Switching the cursor to an image when hovering over an element is causing inconsistency in hover events triggering

Currently, I am attempting to implement an effect that changes the cursor to an image when hovering over a text element and reverts back to the normal cursor upon leaving the text element. However, this functionality is not working as expected when using React in conjunction with standard CSS. At times, the image lingers if the cursor moves diagonally or too quickly in and out of the container.

My goal is to achieve the same effect as seen on :

https://i.stack.imgur.com/3BmOa.gif

Below you can find my code which is not functioning properly along with a fiddle showcasing the issue: https://jsfiddle.net/smyL9v42/

const {useState, useEffect} = React;

function TextWithCursor() {
  const [cursorPosition, setCursorPosition] = useState({ x: 0, y: 0 })

  const handleMouseMove = event => {
    setCursorPosition({ x: event.clientX, y: event.clientY })
  }
  return (
    <div
      className="container"
      onMouseMove={handleMouseMove}
    >
      HELLO
      <img
        src="https://images.unsplash.com/photo-1608877906884-5ffef2ef9612?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&w=200&q=80"
        className="imageWithOpacity"
        alt="Custom cursor"
        style={{
          left: cursorPosition.x,
          top: cursorPosition.y,
        }}
      />
    </div>
  )
}

ReactDOM.render( <TextWithCursor />, document.getElementById('root') );

CSS:

.container {
  border: 1px solid black;
  width: 200px;
  cursor: none;
}

.container:hover .imageWithOpacity {
  opacity: 1;
}

.imageWithOpacity {
  position: fixed;
  opacity: 0;
  height: auto;
  display: block;
}

Here is how it looks when it's broken: https://i.stack.imgur.com/qoftn.gif

Answer №1

Enhancing User Experience

To improve the functionality of your code, consider incorporating pointer-events: none; into the hover image. This will prevent the image from triggering mouse events, addressing the underlying issue. For more information, visit the following resource: pointer-events

Feel free to test the snippet provided below to see this in action.

React Snippet Showcase

const {useState, useEffect} = React;

function TextWithCursor() {
  const [isHovering, setIsHovering] = useState(false)
  const [cursorPosition, setCursorPosition] = useState({ x: 0, y: 0 })

  const handleMouseMove = event => {
    setCursorPosition({ x: event.clientX, y: event.clientY })
  }
  return (
    <div
      className="container"
      style={{
      }}
      onMouseMove={handleMouseMove}
    >
      HELLO
      <img
        src="https://images.unsplash.com/photo-1608877906884-5ffef2ef9612?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&w=200&q=80"
        className="imageWithOpacity"
        alt="Custom cursor"
        style={{
          position: "fixed",
          left: cursorPosition.x,
          top: cursorPosition.y,
        }}
      />
    </div>
  )
}

ReactDOM.render( <TextWithCursor />, document.getElementById('root') );
.container {
  cursor: hidden;
  border: 1px dotted blue;
  width: 200px;
  cursor: none;
}

.container:hover .imageWithOpacity {
  opacity: 1;
}

.imageWithOpacity {
  position: fixed;
  opacity: 0;
  height: auto;
  display: block;
  pointer-events: none;
}
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>

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

Developing an interactive input tab for user engagement

I'm in the process of developing a web application for my current university workplace. Currently, I am seeking guidance on how to create a dynamic user input form for our website using asp.net and c# in visual studio 2017. I'm struggling a bit w ...

Refreshing the page triggers the callback function that retrieves the checkboxes selected in a Kendo treeview component

How can I retain the selected checkboxes after refreshing the page? Is there a way to achieve this using AJAX when submitting data to a database and then reloading the page? AJAX //AJAX call for button $("#primaryTextButton").kendoButton(); va ...

What is the process for appending a file extension to a Next.js URL?

For instance, I am attempting to redirect the URL : https://example.com/data/publications to this : https://example.com/data/publications.json I made an attempt using Next.js redirection, but encountered difficulty when trying to add a string that does no ...

Is there a way for a Vue component to interact with a button or checkbox in order to dynamically update tooltip content and button style using a function?

Is it possible for a Vue component to trigger button clicks or checkbox checks in order to update tooltip text and button color using a function? Despite the presence of a handle() function in the code provided, these changes are not currently taking effec ...

Tips for effectively utilizing the Material-UI Grid component to implement this layout

Currently, I am working on incorporating this design in Material-UI by utilizing the Grid component. To better delineate the boundaries, I have marked the container border in red for clarity. The Add button should be positioned at the far right of the c ...

Utilizing ReactJS and TypeScript to retrieve a random value from an array

I have created a project similar to a "ToDo" list, but instead of tasks, it's a list of names. I can input a name and add it to the array, as well as delete each item. Now, I want to implement a button that randomly selects one of the names in the ar ...

Investigating Jquery Flip Card Issues

Looking to create a set of flip cards using HTML, CSS, and jQuery. Currently facing an issue where only the first card is flipping when clicked. Any suggestions on how to modify the jQuery code to make it work for all cards would be highly appreciated. C ...

Can you explain the purpose and function of stub.callsArg(index) feature in Sinon.JS?

Confusion has set in as I try to make sense of this. According to the documentation: stub.callsArg(index) - This command prompts the stub to execute the callback function found at the specified index. For instance, using stub.callsArg(0); will trigger the ...

Selecting a Child Component in Vue.js: A Guide to Specifying the Correct Component

Within my application, I have a variety of components that are either generic or specific to certain brands. For example, I have two brand-specific components named Product_brand_A.vue and Product_brand_B.vue, both of which I want to display in a list form ...

Using regular expressions to enable scientific notation in a numeric text field

I'm looking to create a validation system for numbers with scientific notation (using 'e', '+', '-', '.') using regex. I've tried some expressions but they are not working as expected. For Regular Numbers: ...

Using JQuery to eliminate Javascript code after setting up an event listener, but prior to the listener being activated

Having trouble finding a solution to my question through search. I'm sorry if it has already been asked before. I am attempting to define an event listener and immediately remove the JS code after defining it. The challenge is that I want the removal ...

Tips for sending props to MUI styled menu for creating specific conditional styling effects

Is it possible to pass props to an already styled Material-UI menu with conditional styling for different minimum widths? The issue I am facing is that the menu's styles are outside of the component receiving the props, so how can I achieve this? c ...

What is the reason behind the modification in flex item size when align-items property is applied?

When creating the responsive design, I utilized flexbox. Surprisingly, without changing the size of each flex-item, applying align-items:center caused the size of the first flex item (PICTURE 2) to change when displayed in a vertical view. On the other han ...

Organizing an array of objects by sorting them according to their internal data and grouping them together

Looking to organize this array of objects in a hierarchical structure: var channels = [{ cid: 5, pid: 10 }, { cid: 10, pid: 0 }, { cid: 20, pid: 5 }, { cid: 15, pid: 10 }]; In this case, cid represents channel Id and pid r ...

Guide on debugging Express.js server code on Node with Visual Studio Code by Attaching to a live process

Here is a list of the tools I have: Latest Visual Studio Code Express js Node js Take a look at my Attach configuration below: { "version": "0.1.0", // List of configurations. Add new configurations or edit existing ones. "configurations": ...

Adjust the width of an element as its content dynamically shifts

I have a container that contains 6 input fields. Two of them are initially hidden (display: none), but when I click on a checkbox, these two inputs become visible (display: inline). I need the width of the container to adjust and increase when the other tw ...

The file import is restricted based on the user's input

I am facing an issue with my small vue.js app. My goal is to import a specific json file based on user input. import content from "@/posts/posts/" + new URL(location.href).searchParams.get('id') + ".json"; Every time I attem ...

ReactJS and JavaScript offer a convenient solution for extracting the most recent date from an array of date fields during the selection process

I have a table in ReactJS that displays an array of items. Each item has the following fields: id, requested_date, and location Additionally, there is another field called "date" which is located outside of the array. This "date" should always display th ...

What is the issue with this asynchronous function?

async getListOfFiles(){ if(this.service.wd == '') { await getBasic((this.service.wd)); } else { await getBasic(('/'+this.service.wd)); } this.files = await JSON.parse(localStorage.getItem('FILENAMES')); var ...

Using Jquery to Redirect Users According to URL Position

My current dilemma involves... I want to create a condition where if the URL specifically contains /foldername/index.htm or /foldername/ on mydomain.com, then it should redirect to http://www.example.com If the URL includes any URL parameter with /folder ...