Event handler for the MouseLeave event is not successfully triggering when dealing with anchor

When viewing a link to a Codepen, the issue is most noticeable in Chrome:

https://codepen.io/pkroupoderov/pen/jdRowv

Sometimes, the mouseLeave event fails to trigger when a user quickly moves the cursor over multiple images, resulting in some images retaining the grayscale filter. How can this be fixed? Switching from an anchor element to a div resolves the issue completely. Should I tweak the markup slightly or apply specific styles to the anchor element? Perhaps leveraging a component from React-Bootstrap could help?

The goal is to create an overlay effect on an image when a user hovers over it, similar to Instagram. The content for the overlay will be added later; currently, the focus is on resolving the mouseLeave event problem.

const imageUrls = [
  'https://farm8.staticflickr.com/7909/33089338628_052e9e2149_z.jpg',
  'https://farm8.staticflickr.com/7894/46240285474_81642cbd37_z.jpg',
  'https://farm8.staticflickr.com/7840/32023738937_17d3cec52f_z.jpg',
  'https://farm8.staticflickr.com/7815/33089272548_fbd18ac39f_z.jpg',
  'https://farm5.staticflickr.com/4840/40000181463_6eab94e877_z.jpg',
  'https://farm8.staticflickr.com/7906/46912640552_4a7c36da63_z.jpg',
  'https://farm5.staticflickr.com/4897/46912634852_93440c416a_z.jpg',
  'https://farm5.staticflickr.com/4832/46964511231_6da8ef5ed0_z.jpg'
]

class Image extends React.Component {
  state = {hovering: false} 

  handleHover = () => {
    this.setState({hovering: true})
  }
  handleLeave = () => {
    this.setState({hovering: false})
  }

  render() {
    if (!this.state.hovering) {
      return (
        <div onMouseOver={this.handleHover}>
          <img src={this.props.url} alt='' />
        </div>
      )
    } else {
      return ( // works fine when using <div> tag instead of <a> or <span>
        <a href="#" style={{display: 'block'}} onMouseLeave={this.handleLeave}>
          <img style={{filter: 'opacity(20%)'}} src={this.props.url} alt='' />
        </a>  
      )
    }
  }
}

const Images = () => {
  return (
    <div className="gallery">  
      {imageUrls.map((image, i) => {
        return <Image key={i} url={image} />
      })}
    </div>
  )
}

ReactDOM.render(<Images />, document.getElementById('app'))

Answer №1

You can easily accomplish this with just CSS, there's no need for Javascript.

#link {
   display: block;
}

#link:hover {
   filter: opacity(.2);
}

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

Utilize a class method within the .map function in ReactJS

In my ReactJS file below: import React, { Component } from "react"; import Topic from "./Topic"; import $ from "jquery"; import { library } from '@fortawesome/fontawesome-svg-core' import { FontAwesomeIcon } from '@fortawesome/react-fontaw ...

Creating a personalized backend server within Next.js

Embarking on my E-Commerce project using Next.js has led me to delve into its documentation. However, I still have lingering questions as this will be my inaugural Next.js endeavor. Listed below are the specific points I am curious about: Incorporatin ...

Track how far visitors scroll into the inner content area using Google Tag Manager

Our website features a left-side vertical navigation menu. In order to measure scroll depth, we incorporated Tag Manager code. However, the Tag Manager code triggers on every page load due to us fixing the body scroll and implementing a custom scroll for t ...

Navigating back to the original page after venturing to a different one - react

In the header of each page, there is a 'Back' button that allows users to navigate back to the previous page. The function handleGoBack() is responsible for this: import React from 'react'; import { Button, Typography } from "@mate ...

JavaScript file isn't being called by index.html

I am working on establishing a basic client/server connection using node.js modules along with a straightforward HTML page. The content of the HTML page is as follows: <script type="text/javascript" src="index.js"></script> The index.js fi ...

Nested pages in the NextJS router do not properly highlight the active menu item

I am currently working with NextJS and facing an issue with setting active menu items using the router. While the 'top level' pages behave as expected, any page under a top level page does not get set as active. router.pathname == "/profile& ...

What is the best way to display a description overlay on an adjacent image when hovering over it?

Seeking assistance or guidance in the right direction. I have a desire to showcase a grid of images with hover-over functionality for additional information, similar to what can be seen here. Could someone advise if this task is manageable with pure CSS ...

Issues with escaping HTML encoding

Currently working on an Android app that involves querying a webservice and receiving a JsonObject. Once I have the desired String, I encounter characters like: est&amp;aacute; I've experimented with two methods: StringEscapeUtils.escapeHTML4(te ...

Tips for fixing problems with useEffect in Next.js

Is there a way to make useEffect have control over the component update? Consider the following code: const [data, setData] = useState([]); useEffect(() => { fetch("/api/data") .then((res) => res.json()) .then((res) => { ...

Guide: Implementing material-ui theme with redux in gatsby

I'm currently utilizing the material-ui theme in conjunction with redux-toolkit within a gatsby project. This is my theme.ts file: import { createMuiTheme } from "@material-ui/core"; import { useSelector } from "react-redux"; import { State } from ". ...

Notifications for AngularJS tabs

I need help finding a method to incorporate "tab notification" using AngularJS, in order to show that there are important alerts that require attention. For example: (1) (3) TAB_ONE TAB_TWO TAB_THREE Could you provide any recom ...

What is the reason for React's progressive bar displaying the complete percentage instead of progressively increasing it?

I am attempting to update the percentage state by adjusting setTimeout during the page load process, causing the filler to gradually fill the progressiveBar up to 100%. const { React, ReactDOM } = window const { useEffect, useState, Fragment } = React c ...

Is there a more efficient method for showcasing model objects in Thymeleaf rather than utilizing a form?

I've been exploring Spring Boot, Thymeleaf, and frontend development in general. Currently, I have a frontend table that displays a list of objects from the backend, along with a form to allow users to view properties of each item in the list. Howeve ...

Developing a dynamic row that automatically scrolls horizontally

What is the best method for creating a div box containing content that automatically slides to the next one, as shown by the arrows in the picture? I know I may need jquery for this, but I'm curious if there's an alternative approach. oi62.tinyp ...

State not getting updated with array passed to this.setState()

Within an array, I have stored the following credentials: //The Snippet variable is an array that looks like this { details: test, _id: "5d9d0b506ee7d03a54d8b1f6", name: "TEST GREEN", content: "<div style="background-color:green; height:100px; widt ...

What is the best way to create an L shape using CSS?

I am currently working on achieving a unique style using CSS. https://i.sstatic.net/bJlok.png My progress so far: .file { width: 279px; height: 326px; background: linear-gradient(-135deg, transparent 66px, #A1A1A4 40px); position: relative; } ...

Developing with Phonegap Build: A Guided Process

With all the conflicting information available, I am seeking clarity on this topic. Objective: To create and enhance a Phonegap app using Phonegap Build. 1) My preference is to utilize Phonegap Build without needing to install Android and iOS SDKs. 2) I ...

Troubleshooting React using breakpoints: A step-by-step guide

Currently I am working with Chrome and facing an issue. For instance, I require Component.jsx and want to set a breakpoint at a specific location. When I press F12, navigate to the Sources tab, and use Ctrl+P to search, I only find 1.chunk.js, bundle.js, ...

Is there a way to verify if the data_URL is specifically delivering a video or image file? - Utilizing Firebase with Next.js/React

After uploading the image to Firebase, it is returned as a unique data URL format: https://firebasestorage.googleapis.com/v0/b/app_name/o/posts%2postId?alt=media&token=token The challenge lies in determining whether the file type is a video or an imag ...

I am having trouble with my scroll reveal effects on JavaScript, how can I troubleshoot and fix the issue?

I'm currently making updates to my portfolio website, but for some reason, the scroll reveal animation has suddenly stopped working. I made a few edits and now it seems to be broken. /*===== SCROLL REVEAL ANIMATION =====*/ const sr = ScrollReveal({ ...