I want to create the same animation for the left text on my website as seen on this website using React and CSS. So far, I’ve tried the following code, but it doesn’t achieve the same effect:
const Home = () => {
const btRef = useRef();
useEffect(() => {
btRef.current.querySelectorAll('div').forEach(wrapTextWithSpans);
document.addEventListener('mousemove', function (e) {
const spans = btRef.current.querySelectorAll('span');
spans.forEach((span) => {
const rect = span.getBoundingClientRect();
const spanCenterX = rect.left + rect.width / 2;
const spanCenterY = rect.top + rect.height / 2;
const distance = Math.hypot(
e.clientX - spanCenterX,
e.clientY - spanCenterY
);
const maxDistance = 250; // Maximum distance for effect
const weights = [1000, 900, 800, 700, 600, 500]; // Font weights
let fontWeight;
if (distance < maxDistance) {
const weightIndex = Math.floor(
(distance / maxDistance) * (weights.length - 1)
);
fontWeight = weights[weightIndex];
} else {
fontWeight = weights[weights.length - 1];
}
span.style.fontWeight = fontWeight;
});
});
}, []);
const wrapTextWithSpans = (element) => {
const text = element.innerText;
element.innerHTML = '';
for (const char of text) {
const span = document.createElement('span');
span.innerText = char;
element.appendChild(span);
}
};
return (
<div className={styles.home}>
<div className={styles.homeContent}>
<div
className={styles.boldText}
ref={btRef}
>
<div className={styles.boldLine}>Let's build a brand</div>
<div className={styles.boldLine}>together that</div>
<div className={styles.boldLine}>you and your</div>
<div className={styles.boldLine}>community will</div>
<div className={styles.boldLine}>be proud of.</div>
</div>
</div>
);
};
As you can tell from the code, I want to apply the effect only to the text under the boldText class. Generally, what happens is that the text under the mouse and the surrounding text become bolder, and as you move away from the mouse, it gradually returns to normal. Additionally, the text around the mouse seems to stretch, but I haven’t figured out that part exactly. How can I achieve this?