How to fade out a div slide using CSS animations?

Viewed 63

I made a simple slide show with divs stacked one on top of the other. I switch the div on display with display:none or display:block.

But when I add animations, I encounter a problem. The fade in works, but I have no idea how to fade out a vanishing slide. The slide just disappears and I can't get any fade out method that I have found to work. Where is the error please?

let pages = document.getElementsByClassName("page");

let buttons = document.getElementsByClassName("page-button");

let currentPage = 0;
pages[currentPage].style.display = "block";
for (let i = 0; i < buttons.length; i++) {
  buttons[i].addEventListener("click", () => changePage(i));
}

function changePage(k) {
  pages[currentPage].style.display = "none";
  pages[k].style.display = "block";
  currentPage = k;
}
.content-container {
  display: flex;
  height: 90vh;
}

.page {
  position: absolute;
  display: none;
  width: 100%;
  height: 100%;
  animation: fadeIn 3s;
}

@keyframes fadeIn {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

#slideshow {
  flex-grow: 1;
  position: relative;
}
<div class="content-container">
  <div id="slideshow">
    <div class="page" style="background-color: red;"></div>
    <div class="page" style="background-color: green;"></div>
    <div class="page" style="background-color: blue;"></div>
  </div>
  <button class="page-button">1</button>
  <button class="page-button">2</button>
  <button class="page-button">3</button>
</div>

2 Answers

The issue is that you are using a display none, which will instantly remove the coloured block and fade in from white.

On click set the background colour of the 'content-container' to the item's colour to be removed, giving the impression of fading in from that colour.

    var contentContainer = document.getElementsByClassName("content-container");

    var replaceColour = pages[k].styles.getPropertyValue("background-color")
    
    contentContainer.style.backgroundColor = replaceColour;

For animation I use the library called Animate.css. Take a look at the following link:

https://animate.style/

You can install this library with NPM:

npm install animate.css --save

Then you can use this library like this:

<div class="page animate__fadeOutLeft" style="background-color: green;">

Related