Simple Spotlight


by Jeremy Caudle
code

I wanted to try out a spotlight that follows the cursor’s position. It turns out this is fairly easy to do if you use CSS custom properties and the mousemove event. The spotlight is a little offset within this code post. I’ll have to sort out why in a future post.

View the code:

HTML and JS
<div id="code" class="code-block">
            <div id="spotlight"></div>
   
        </div>
        
        <script>

            // ---------        
            // Variables
            // ---------
            const codeBlock = document.getElementById('code');
            const cursorSpotlight = document.getElementById('spotlight');
            

            // ---------
            // Functions
            // ---------
        
            function updateSpotlightPosition() {
                document.body.addEventListener('mousemove', (event) => {
                    let mouseX = event.x;
                    let mouseY = event.y;
                    cursorSpotlight.style.setProperty('--mouse-x', `${mouseX}px`);
                    cursorSpotlight.style.setProperty('--mouse-y', `${mouseY}px`);
                    console.log(event.x, event.y);
                })
            }

            // ---------        
            // Events
            // ---------
         
            //Run function every 1/10 second.
            setInterval(updateSpotlightPosition, 200);

        </script>
CSS
.code-block {
                margin: 0;
                padding: 0;
                display: block;
                width: 100%;
                background-color: black;
                height: 50vh;
								position: relative;
                z-index: 1;
								overflow: hidden;
            }

            #spotlight {
                height: 6rem;
                width: 6rem;
                background-color: #ffffff;
                opacity: .25;
                clip-path: circle(50% at 50%);
                border-radius: 50%;
                position: absolute;
                margin: -3rem 0 0 -3rem;
                left: var(--mouse-x, 1px);
                top: var(--mouse-y, 1px);
                z-index: 2;
                filter: blur(10px);
            }