javascripthtmlonmouseoveronmouseout

Onmouseover and mouseout keeps blinking & firing


I have columns and I want to display images when my mouse goes over the images, however, mouseover and mouseout keeps firing when i move on the same image. So the images keep blinking. How can I resolve this?

I filtered the image class (media-overlay) to change its display

this is my example https://jsfiddle.net/saltykiam/bw4ap70v/5/

let row = document.getElementById("row");

    row.onmouseover =(e)=>{    
    [...e.path].filter(element => 
      element.classList && element.classList.contains("media-overlay"))[0].style.display = "none";
    }
    
    row.onmouseout =(e)=>{    
    
    [...e.path].filter(element => 
      element.classList && element.classList.contains("media-overlay"))[0].style.display = "block";
    
    }

Solution

  • The issue is that when you call your 'onmouseover' event, the image is being set to

    display: none;
    

    This actually removes the image from the page, so now when you move your mouse anywhere you're actually calling your "onmouseout" event. This is because the image is no longer on the page, has no physical dimensions, and so any movement of the mouse is considered moving your mouse out of the image.

    To fix this, apply the style change against opacity rather than display. Set opacity to 0 for when you want the image to disappear:

    row.onmouseover = (e) => {
      [...e.path].filter(element =>
        element.classList && element.classList.contains("media-overlay"))[0].style.opacity = 0;}
    

    and set the opacity to 1 when you want the image to reappear:

    row.onmouseout = (e) => {
      [...e.path].filter(element =>
        element.classList && element.classList.contains("media-overlay"))[0].style.opacity = 1;}