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

Having trouble getting Vue.js hello world to display on the page

I am attempting to create a Hello World app following the Vue.js site's get started documentation. Everything seems to be in order, but only the HTML code is being displayed on the page. Vue version: 1.0.26 Below is the HTML code: <!DOCTYPE ht ...

Locate the position of the cursor within a rectangular shape

I'm struggling to determine the location of a cursor within a rectangle, specifically which part (one of 4 triangles) it is in. This visual representation helps me grasp it better than any explanation I can come up with :s Working in javascript (whe ...

Assign a value to a cookie using Node.js

I'm currently working on a web project using node.js and express. What is the best way to establish a cookie value? ...

Having trouble with jqGrid data format?

Having some trouble with jqGrid and displaying data in a treeview format. The issue is that the 6th item (cid=6) is not appearing in the grid. Additionally, it seems like the 4th item may have subitems, but expanding that branch reveals nothing. I cannot f ...

Differences between JSX.Element, ReactNode, and ReactElement: When should each be utilized?

Currently in the process of transitioning a React application to TypeScript. Everything seems to be going smoothly, however I've encountered an issue with the return types of my render functions, specifically within my functional components. In the p ...

Scroll bar for multiple selection select tag without using div element (not supported in firefox)

.selector select[multiple="multiple"] { border-radius: 0; height: 200px; margin: 0 0 0 -1px; max-width: 368px !important; padding-left: 3px; width: 368px !important; } <select id="id_included_packages_from" class="filtered" multiple="multipl ...

How to determine the length of a JavaScript object

Would like help determining the length of the report_data(object) key using the provided code, but it seems to result in a value of 3. a={report_freq: "daily", report_item_num: 2, report_num: 39, report_data: "{}"} Object {report_freq: "daily", report_ite ...

Should using module.export = [] be avoided?

Having two modules that both need access to a shared array can be tricky. One way to handle this is by creating a separate module just for the shared array, like so: sharedArray.js module.exports = []; In your module files, you can then use it like this ...

My Angular7 app.component.html file is not displaying the routing. What could be the issue?

After implementing the code in app.component.html in Angular 7 like this: <div id="wrapper"> <header id="header-container" class="fullwidth"> <div id="header"> <div class="container"> <div class="left- ...

My React project is unable to import the foundation SCSS file into the App.scss file

After installing zurb-foundation using npm, I attempted to import the .scss file into my App.scss file. Utilizing the "live sass server" for compiling the .scss code into .css code, a .css file was generated but did not display any code despite successfull ...

When a page is being redirected using requestdispatcher in a filter, the CSS contents do not seem to be applying correctly

Upon evaluation of the condition, if it fails, I am utilizing a request dispatcher to redirect to another page. The redirection is successful, however, the CSS is not being applied to the new page. What could be causing this issue? public class RolePrivil ...

What is the method for accessing the value of variable "a" in the following code?

request(target, function (err, resp, body) { $ = cheerio.load(body); links = $('a'); $(links).each(function (i, link) { if ($(link).text().match('worker')) { var a = $(link).attr('href').toStri ...

Target the select element with a specific style applied, but restrict it to only be selected when nested within a div that shares the same style

Not quite sure about the effectiveness of the title, but here's what I'm attempting to accomplish. <div class="mystyle"> <select name="somename" id="somename"> <option value="Value1"> <option value="Value2" ...

Preventing Duplicate Random Numbers in Vue 3 and JavaScript: A Guide

I've been working on creating a function that can iterate through an array of objects with names and IDs, randomize the array, and then return one filtered item to slots.value. The current spin function successfully loops through the randomized object ...

Content width exceeds body width

Having an issue with body width that seems strange. Check out this fiddle link to see for yourself. <div class="topbar" style="width:100%; background:#000; color:#fff"> <div class="container" style="width:970px; margin:0 auto;">Lorem ipsum ...

The GMaps API v3 is currently being loaded, but is not displaying on the webpage

Although the maps are supposed to be loading, I'm having trouble actually seeing them appear. Troubleshooting function initialize() { var myLatlng = new google.maps.LatLng(-25.363882,131.044922); var mapOptions = { zoom: 4, center: myLat ...

Intrigued by the connection between background and calc()?

Hello everyone! I'm currently involved in a project and have a quick question regarding the calc function. As we all know, it functions perfectly on all browsers... ========== great! ============= background-color:#dfdfdf; background-image:url(..) ...

Customizing Bootstrap icon with padding, background color, and radius settings

Struggling with Bootstrap Icons and Bootstrap 5, I attempted to create a perfect circle background behind an icon by setting padding, background color, and a rounded circle radius. The code I used was <i class="bi-globe-americas text-white p-3 bg-p ...

Is it just me, or does floating right not seem to work on 404 pages?

I have been working on setting up a unique header and footer design for a client's website. You can check it out here: Everything is looking good with the social media links floating to the right on all pages, except for some reason on the 404 error ...

The input form in my Node.js project is not adapting to different screen sizes. I am currently utilizing ejs as the template

I have integrated ejs as a template in my Node.js project, but I am encountering an issue with the input form in the following code snippet. The form is unresponsive, preventing me from entering text or clicking on any buttons. What could be causing this ...