JSFiddle - React, Tailwind, and code Playground
by frolicked
HTML
<div class="content">
<div class="spotlight"></div>
</div>
CSS
.content {
position: relative;
width: 640px;
height: 480px;
background: url(https://bekahaytch.files.wordpress.com/2020/11/unhygge_dark.png) no-repeat 0 0;
overflow: hidden;
}
.spotlight {
display: none;
position: absolute;
background: url(https://bekahaytch.files.wordpress.com/2020/11/unhygge.png) no-repeat 0 0;
}
JavaScript
// Global variables
var spotlightDiameter = 250;
// Verify that the mouse event wasn't triggered by a descendant.
function verifyMouseEvent(e, elem) {
e = e || window.event;
var related = e.relatedTarget || e.toElement;
while ((related != undefined) &&
(related != elem) &&
(related.nodeName != 'BODY'))
{
related = related.parentNode;
}
return (related != elem);
}
// Create the spotlight
function createSpotlight() {
jQuery('.spotlight').width(spotlightDiameter + 'px')
.height(spotlightDiameter + 'px')
.css({borderRadius: (spotlightDiameter >> 1) + 'px'});
}
// Mousemove
jQuery('.content').on('mousemove', function(e){
var center = {x: e.pageX - this.offsetLeft,
y: e.pageY - this.offsetTop};
var x = center.x - (spotlightDiameter >> 1);
var y = center.y - (spotlightDiameter >> 1);
jQuery('.spotlight').css({left: x + 'px', top: y + 'px',
backgroundPosition: -x + 'px ' + -y + 'px'}).show();
});
// Mouseover
jQuery('.content').on('mouseout', function(e){
if (!verifyMouseEvent(e, this)) return;
$('.spotlight').hide();
});
jQuery(document).ready(function(){
createSpotlight();
});