Search code examples
javascripthtmlcssreactjstailwind-css

How can I create the effect of a background partially disappearing when I hover with the pointer?


I'm attempting to create a scenario where I have two divs, and when hovered over, the background of one div should partially disappear, resembling a small circle around the pointer.

<div className='bg-img1 h-32 w-32 bg-no-repeat bg-cover bg-center' id='div1'>
  <div className='bg-img2 h-32 w-32 bg-no-repeat bg-cover bg-center' id='div2'></div>
</div>

The idea is that when hovering over div1, the background should fade away in a circular pattern around the pointer, and this effect should follow the movement of the pointer. Is there a way to achieve this?

PostData: I'm using React JS and TailWind Css.

I've attempted to search for solutions related to making a background react to the pointer in React, but the results mostly provided information on creating a circle that follows the pointer rather than achieving the specific effect I'm looking for.


Solution

  • If I'm understanding correctly, you're aiming to uncover the background of div1 as we hover the cursor over div2.

    The provided code utilizes the .partial-disappear class, masking the background with variable --x and --y, enabling this functionality

    const div2 = document.getElementById('div2');
    const div1 = document.getElementById('div1');
    
    div2.addEventListener('mousemove', (e) => {
      const x = e.clientX - e.target.getBoundingClientRect().left;
      const y = e.clientY - e.target.getBoundingClientRect().top;
      div1.style.setProperty('--x', `${x}px`);
      div1.style.setProperty('--y', `${y}px`);
      div2.classList.add('partial-disappear');
    });
    
    div2.addEventListener('mouseleave', () => {
      div2.classList.remove('partial-disappear');
    });
    /* Set height and bg-size */
    #div1,#div2 {
    height:400px;
    background-size:cover;
    background-position:center;
    }
    
    /* Set background */
    #div1 {
      background-image: url('https://images.unsplash.com/photo-1529619768328-e37af76c6fe5?q=80&w=1887&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D');
    }
    
    #div2 {
      background-image: url('https://images.unsplash.com/photo-1548850174-70a1cf2c5f09?w=600&auto=format&fit=crop&q=60&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxzZWFyY2h8N3x8bmlnaHQlMjBjaXR5fGVufDB8fDB8fHww');
    }
    
     /* Partially hide the background of div2. Set 'transparent' and 'black' value accordig to your requirement */
    .partial-disappear {
      mask: radial-gradient(circle at var(--x) var(--y), transparent 70px, black 120px);
      -webkit-mask: radial-gradient(circle at var(--x) var(--y), transparent 70px, black 120px);
    }
    <div class="bg-img1 h-32 w-32 bg-no-repeat bg-cover bg-center" id="div1">
      <div class="bg-img2 h-32 w-32 bg-no-repeat bg-cover bg-center" id="div2"></div>
    </div>