Home > Software design >  Collapsing a div with Animation: how to improve this code?
Collapsing a div with Animation: how to improve this code?

Time:02-28

I'm trying to make a div that appear and disappear on touch, like the navigation bar of android phones. Should I use transition for this or is animation ok? In the fiddle example i use the mouse click and the setTimeout to simulate the touches and the auto disappear if you dont touch the screen for some seconds.

.custom-row{
  position: fixed;
  width: 100%;
  height: 50px;
  bottom: -100px;
  left: 0px;
  background-color: yellow;
  opacity: 0;
}

    .slidein {
        animation: slidein 1s ease-in forwards;
    }

    .slideout {
        animation: slideout 1s ease-in forwards;
    }

    @keyframes slidein {
        0% {
        }

        100% {
            bottom: 0px;
            opacity: 1;
        }
    }
    
    @keyframes slideout {
        0% {
            bottom: 0px;
            opacity: 1;
        }

        100% {
           bottom: -100px;
            opacity: 0;
        }
    }

https://jsfiddle.net/1rm64q8z/1/

CodePudding user response:

For this use case, transition seems to be a better solution. With animation, alerting position is a compute-intensive approach. The CSS will also be much more readable and scalable with transitions in this case.

const bar = document.getElementById("bottom-bar");

bar.addEventListener("click", (el) => {
  el.target.classList.toggle("slide-out");

  setTimeout(() => {
    el.target.classList.toggle("slide-out");
    el.target.classList.toggle("slide-in");
  }, 2000)
})
body {
  overflow: hidden;
}

#bottom-bar {
  position: absolute;
  bottom: 0px;
  left: 0px;
  width: 100%;
  background: yellow;
  padding: 16px;
  text-align: center;
  transform-origin: bottom;
  transition: transform 0.4s ease-in-out;
}

.slide-in {
  transform: translateY(0%);
}

.slide-out {
  transform: translateY(100%);
}
<div id="bottom-bar">
  Hello
</div>

CodePudding user response:

The performance of CSS transitions and animations should be almost the same as they are both hardware accelerated so on most modern browsers the behaviour should be the same.

Animations are often used to create a more complex series of movements and they do not lift the rendering process to the GPU and resulting in being slower than transitions.

This article gives a great breakdown of when to use animations vs transitions.

  • Related