0

I'm using animation property CSS to animate the window when the user clicks maximize button. The window is created ONLY when the maximize button was clicked and the animation is working, but the problem is when I click the close button the window is doesn't animate. How can I animate when the close button is click?

JavaScript:

Show project image.

_showProjectImage(e) {
  const btn = e.target.closest('.projects__maximize-btn');
  if (!btn) return;
  const { id } = btn.dataset;
  const { image } = this._data.find(image => image.id === +id);

  this._projectBox = e.target.closest('.projects__box');
  const markup = this._generateProjectImage(image);
  this._projectBox.insertAdjacentHTML('afterbegin', markup);
}

Hide project image.

_hideProjectImage(e) {
  const btnClose = e.target.closest('.btn__close-window');
  if (!btnClose) return;
  this._projectBox.removeChild(this._projectBox.firstElementChild);
}

HTML Element:

_generateProjectImage(image) {
  return `
    <div class="projects__window">
      <div class="projects__window-content">
        <button class="projects__window-close btn__close-window">
          <svg class="projects__window-icon">
            <use
              xlink:href="${icon}#icon-close"
            ></use>
          </svg>
        </button>
        <div class="projects__window-box">
          <img src="${image}" alt="" class="projects__window-image">
        </div>
      </div>
    </div>
  `;
}

CSS:

.projects {
  &__window {
    position: fixed;
    inset: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    z-index: 1000;
    animation: window-animate 300ms linear;
  }
}


@keyframes window-animate {
  from {
    transform: scale(0);
    opacity: 0;
  }
  to {
    transform: scale(1);
    opacity: 1;
  }
}
J.Wujeck
  • 280
  • 4
  • 16
  • 1
    You'll need an animation that does the opposite (or try and set `animation-direction` dynamically, but that alone will probably not trigger a re-run), and you will have to let the animation run first, and only remove the element when that's done (because what you already removed, you can't animate _afterwards_ any more.) – CBroe Mar 14 '22 at 09:19
  • I created an opposite animation for the close button. But I don't know where to put it. – J.Wujeck Mar 16 '22 at 07:32
  • You will need to add a new class or something at this moment, so that the animation triggers, https://stackoverflow.com/questions/44846614/trigger-css-animations-in-javascript And then you will have to either subscribe to the `animationend` event, or use an old-fashioned timeout, to only actually remove the element, when the animation has finished. (Using the event has the advantage that it will be dynamic, no matter how long your animation duration is. If you used a timeout, you would have to specify the duration a second time in the JavaScript.) – CBroe Mar 16 '22 at 07:36

0 Answers0