JSFiddle - React, Tailwind, and code Playground

by Darker

HTML

<div id="animated">Contents of this dif should fade as you move mouse away from it</div>

CSS

* {
    margin: 0px;
    padding: 0px;
    
}

#animated {
    font-family: monospace;
    color: yellow;
    background-color: black;
    width: 100px;
    height: 100px;
    display: inline-block;
    padding: 3px;   
    
    
}

JavaScript

var element = document.getElementById("animated");
window.addEventListener("mousemove", function(e) {
    var rect = element.getBoundingClientRect();
    //Measuring distance from top-left corner of the div
    var top = rect.top+(rect.bottom-rect.top)/2;
    var left = rect.left+(rect.right-rect.left)/2;
    //Mouse position
    var x = e.clientX;
    var y = e.clientY;
    //Thank pythagoras for this
    var distance = Math.sqrt(Math.pow(x-left, 2)+Math.pow(y-top, 2));
    //Brightness in interval <1, 0.1>
    var brightness = Math.min(1, Math.max(0.1, 50/distance));
    
    element.style.opacity = brightness+"";  
    
});