Web Components On Fire
How can I make CSS respond to the mouse? Of course, the :hover
pseudo class has been one of
the basic selectors right from the beginning. But, along with its lesser used cousin :active
, it’s pretty
much the only way that CSS can know what the mouse is doing.
The <hotfx-mouse-move>
element turns mousemove
events in JavaScript into
CSS variables that you can use to style elements.
To see how it works, drag your mouse around the rectangle below and see how the variables change. The component draws a
Cartesian plane over the element, with the top left corner being 0,0
and the bottom right being
1,1
.
Note: It looks like you’re looking at this on a device without a mouse. Touch screens also create mouse events but you’ll have to be tapping all over the place to get the demos here to do anything. To be totally honest, it’s just not going to work very well and you may be better off just opening this on your laptop when you get the chance.
This is one of the simplest HotFX component created so far with only about 30 lines of code. But don’t let that fool you: this component gives your CSS completely wild new powers and your own creativity will be the biggest limit here.
You can see in the demo above that this is a unitless value. What can you do with a unitless value in CSS? Almost anything. Let me demonstrate by showing you how this could turn a normal mesh gradient into something totally psychedelic.
There’s something really interesting about this demo. Usually to get smooth movement of styles we need to use an easing
function like ease-out
or its friends. The movement here has no easing yet it’s still totally smooth
because it’s the user who is moving it.
Also consider what happens when you move your mouse really fast over that gradient: it gets totally nuts and the colors are flashing like crazy. If you came to a page and I did that to you you’d probably be offended or grossed out and leave immediately.
But here you’re doing it to yourself and you can stop instantly whenever you want. When you stop the flashing stops and suddenly there’s no movement at all. This high level of user control makes this very different from most effects we see on the web.
Here’s how you can use this yourself. First add this script to your page:
Then wrap the element you want to animate with the custom element:
<hotfx-mouse-move>
<div>Whatever</div>
</hotfx-mouse-move>
The element will set two custom properties: --hotx-mouse-x
and --hotfx-mouse-y
which you can
then use in your CSS in a calc()
function.
transform: translateY(calc(100px * --mouse-x));
You can use that to modify any CSS property that has a number: transforms, color, opacity, filters, you name it.
Rather than try to ruin this by explaining it any more, how about learning by example with some demos?