Card reveal on hover

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

Thank you!