Open 9am opened 8 months ago
Let's take a moment to think about how to implement this on the web:
It probably goes like this:
HTML
.CSS
, like position: absolute
.mousemove
event listener with JavaScript
, in the handler, and move those boxes according to the offset value to the center position.But, is it possible to do it without JavaScript
? In other words:
For an effect relying on the position of
MouseEvent
, is there a way to track the 'mouse' using just CSS?
𐄡
## Build The Sensor ␥
### The MouseEvent in CSS ␥
We're looking for something in CSS that can be changed by `MouseEvent`, which gives us only 1 option: **Pseudo-classes**, specifically [User action pseudo-classes](https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes#user_action_pseudo-classes).
> For example, the style under `button:active` kicks in when the user presses down the button.
When comes to the `mousemove`, `:hover` is what we need. Consider this: On top of the target, we can apply a sensor layer, which is composed of small sensor cells. While the cursor moves inside the target, the sensor cells under the cursor will be `:hover-ed` accordingly. If we can collect the `index` of the `:hover-ed` cell, it can be used to calculate the `x` `y` coordinates, like the `MouseEvent` could give us.
Let's build a 2*2 sensor:
```html
𐄡
## Build The Effect ␥
Now get back to the effect at the beginning. To replace step-3, instead of writing JavaScript, insert the sensor. Now we have the `(--x,--y)`, throw some `perspective-3d` movement, and we can do it with pure CSS.
> ![demo](https://github.com/9am/9am.github.io/assets/1435457/f6e76803-1fbf-4464-b112-e8bdc54405db)
>
> Edit in [Codepen](https://codepen.io/9am/pen/MWZNaMM)
𐄡
## Closing thoughts ␥
The drawback of this solution is the redundancy of similar declarations for the sensor. There is no way to get rid of them currently unless something like `counter-value()` can be used with `calc()`, which has always been the feature I wanted the most for CSS. There is a discussion about this [here](https://github.com/w3c/csswg-drafts/issues/1026).
But in cases we can not use `JavaScript`, and don't need it to be super accurate, it's always good to know we have options.
---
> ## @9am 🕘
> * Read more [articles](https://9am.github.io) at [9am.github.io](https://9am.github.io)
> * Find other [things](https://www.npmjs.com/search?q=%409am) I built on [GitHub](https://github.com/9am) and [NPM](https://www.npmjs.com/~9am)
> * Contact me via [email](mailto:tech.9am@gmail.com)
> * [![Creative Commons License](https://i.creativecommons.org/l/by-nc-nd/4.0/80x15.png)](http://creativecommons.org/licenses/by-nc-nd/4.0/)