htmljquerycsscss-transitionsclip-path

Let overlay div become visible through clip-path circle transition / animation


I have two <div>s that fill the entire page. The first div (blue) is shown initially and the second one (yellow) is hidden (display:none). If I click on the blue div, I want to show the yellow overlay div. Then, if I click on the yellow div, I want it to disappear.

That works so far if I simply toggle between display:block and display:none using jQuery. Then I can switch between the two divs.

How could I add a transition effect for the situation when switching from display:none to display:block (and, in the best case, vice versa)?

I'd love an opening/closing circle!

I don't know if this is possible in plain CSS plus JavaScript plus jQuery. If it's possible, I guess it might revolve around clip-path and transition? If possible, I'd like to avoid a heavy third-party library just for this animation effect.

Please see my sketch: Sketch of divs and transition

Thank you very much for your advice!


Solution

  • You can animate the clip-path property. You just have to make sure to use circle in both cases (or at least the same for both states). I used 75vmax as the final circle size but this is just eye balling. To be 100% sure that the whole screen is covered you should probably use a calculation for that depending on your screen size or the area you want the circle to cover. You can easily find the math for that online.

    let card = document.querySelector('.card');
    card.addEventListener('click', e => card.classList.toggle('card--overlay'));
    .card {
      position: relative;
      width: 100vw;
      height: 100vh;
      background-color: blue;
    }
    .card.card--overlay .overlay {
      clip-path: circle(75vmax at 50% 50%);
    }
    
    .overlay {
      position: absolute;
      inset: 0;
      background-color: yellow;
      clip-path: circle(0% at 25% 75%);
      transition: clip-path 1s ease;
    }
    <div class="card">
      <div class="overlay"></div>
    </div>