This month I gave a small talk on CSS Variables in Tenerife. It was an intro to the syntax and how to use the feature. I had the chance to meet some awesome co-speakers and attendees, as well as the organizers of the event, the team behind CanariasJS.
One of the last concepts I explored during the talk was using JS to update the CSS variables. It provides a quick way to separate logic and presentation. Using this approach JS doesn't have to override any CSS variables.
With this idea in mind, I set up an event listener for the mousemove
event. This allows me to update the CSS variables with the mouse position directly. By doing this, I'm not using inline styles, or overriding any CSS styles from JS. My code in CSS stays as it is, with only a change in the value of a variable!
document.addEventListener("mousemove", event=> {
const x = event.clientX / window.innerWidth
const y = event.clientY / window.innerHeight
document.documentElement.style.setProperty("--mouse-x", x)
document.documentElement.style.setProperty("--mouse-y", y)
})
With that done, all that's left is writing the CSS to utilize those variables. In this case, we are transforming them to a percentage, and using them as part of a radial background.
.light {
--x-coordinate: calc(100% * var(--mouse-x, .5));
--y-coordinate: calc(100% * var(--mouse-y, .5));
background-image: radial-gradient(
circle at var(--x-coordinate) var(--y-coordinate),
transparent,
black 80px
);
}
This allows us to build a simple radial gradient that moves with the mouse. To see it in action, I have found a very shy monkey 🙈, which is hiding in the page & every time you find it, it will move to a random location on the page. Can you spot it?.