Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
November 27, 2022 06:56 am GMT

Card reveal on hover

Let's create a hover effect to incrementally reveal the card's content.

This effect is pretty simple, within the card we have 2 things, the content and the 'spotlight' or circle. The trick is to make the spotlight to follow the cursor within the card's bounds and the more it moves the bigger it gets.

Functionality

So for each card we want to listen for any mouse movement. let's create a function for that:

function onHoverCard(card) {    const cardSpotlight = card.querySelector('.card__spotlight');    let size = 50;    card.addEventListener('mousemove', (e) => {        const { x, y } = card.getBoundingClientRect();        const mouseX = e.clientX - x;        const mouseY = e.clientY - y;        const cardSpotlightX = mouseX - cardSpotlight.offsetWidth / 2;        const cardSpotlightY = mouseY - cardSpotlight.offsetHeight / 2;        size += 2.5;        cardSpotlight.style.setProperty('--_spotlight-size', `${size}px`);        cardSpotlight.style.transform = `translate(${cardSpotlightX}px, ${cardSpotlightY}px)`;    });    card.addEventListener('mouseleave', () => {        size = 50;    });}

To attach the spotlight element to the mouse within the card's bounds, we first need to find the card's x and Y coords in relation to the page. Then we find the current x and y coords from the mouse event being fired. With those we can calculate the spotlight's coords. Well, just to make the spotlight right in the middle of the cursor we need to deduct half of its size from the coords. Finally, we use the CSS transform property to move the element to the correct coords.

To make the spotlight grow we increment its size everytime the mouse moves and we reset it when the mouse leaves the card. We do this by keeping track of its current size with a variable (size).

Aaaand that is pretty much it!

Here is a demo

My Twitter

Checkout my blog

Thank you!


Original Link: https://dev.to/sarmunbustillo/card-reveal-on-hover-36id

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To