Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript/CSS - animation duration in pixel per second

How can i set the duration of an transition/animation to pixel per second?

You see the two different wrappers, with a different total height depending on it's colored content. The total speed is the same, given from the css transition attribute, thats okay if you want several animations with the same duration. For a smoother look i want to set this transition/animation effect to pixel per second so it takes as long as many pixels there. More content = more pixel = longer animation.

How can i achieve this with vanilla javascript or even css?

var wrapper1 = document.getElementById('wrapper1');
var wrapper2 = document.getElementById('wrapper2');
var header1 = document.getElementById('header1');
var header2 = document.getElementById('header2');
var wrapper1CmputedHeight = wrapper1.scrollHeight;
var wrapper2CmputedHeight = wrapper2.scrollHeight;

header1.addEventListener('click', function() {
  if (wrapper1.style.height === '60px') {
    wrapper1.style.height = wrapper1CmputedHeight + 'px';
  } else {
    wrapper1.style.height = '60px';
  }
})

header2.addEventListener('click', function() {
  if (wrapper2.style.height === '60px') {
    wrapper2.style.height = wrapper2CmputedHeight + 'px';
  } else {
    wrapper2.style.height = '60px';
  }
})
#wrapper1,
#wrapper2 {
  background: #fff;
  border: 1px solid grey;
  overflow: hidden;
  transition: height .2s linear
}

#wrapper1 {
  margin-bottom: 40px
}

#header1,
#header2 {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer
}

#content1 {
  height: 20px;
  background: blue
}

#content2 {
  height: 600px;
  background: green
}
<div id="wrapper1" style="height: 60px">
  <div id="header1">
    <span>header</span>
  </div>
  <div id="content1"></div>
</div>

<div id="wrapper2" style="height: 60px">
  <div id="header2">
    <span>header</span>
  </div>
  <div id="content2"></div>
</div>
like image 479
Flo Avatar asked Oct 28 '22 22:10

Flo


1 Answers

The only way to do this with css transitions, is to dynamically calculate the duration of the transition using a little javascript. So, in your code, I would remove the duration for the transition rule in your css, i,e.

#wrapper1,
#wrapper2 {
  background: #fff;
  overflow: hidden;
  transition: height linear
}

and I would instead set the duration in the click handler as follows:

header1.addEventListener('click', function () {
    if(wrapper1.style.height === '60px') {
    wrapper1.style.height = wrapper1CmputedHeight + 'px';
    wrapper1.style.transitionDuration=(wrapper1CmputedHeight/100)+"s";
  } else {
    wrapper1.style.height = '60px';
  }
})

So in this case, I've used a speed of 100px per second (this is the /100 part in the above code).

like image 130
redneb Avatar answered Nov 08 '22 12:11

redneb