Towkir
Towkir

Reputation: 4004

How do I set the time duration of an animation using Javascript?

I want a JavaScript function to take the time I provide to execute. I know what setTimeOut() or setInterval() does, I am not looking for them.

For example, I have a div at top: 0 and left: 0. I want my JS function to take the div from left: 0 to left: 50 in the given time.

Please provide a raw JavaScript solution, not jQuery.

Upvotes: 1

Views: 4373

Answers (2)

StardustGogeta
StardustGogeta

Reputation: 3406

var timeInMs = 500;

document.getElementById("test").style.transition = "all "+timeInMs+"ms";
#test {
  background-color: green;
  width: 200px;
  height: 150px;
  margin-left: 0;
}
<div id='test' onclick="this.style.marginLeft = '50px';"></div>

I believe that this is what you are looking for, with no jQuery requirements.

EDIT: I have drafted a new version based on the comments below.

var timeInMs = 500;

document.querySelectorAll("#test *").forEach(function(a){
  a.style.transition = "all "+timeInMs+"ms";
  a.addEventListener("click",function(){
    this.style.margin = 0;
    this.style.opacity = 0;
    this.style.width = 0;
  });
});
#test * {
  background-color: green;
  width: 200px;
  height: 150px;
  margin: 10px;
  display: inline-block;
}

#test {
  background-color: lightblue;
  display: inline-block;
}
<div id="test">
  <div></div><div></div><div></div>
</div>

Upvotes: 0

Oriol
Oriol

Reputation: 287960

Web Animations defines the experimental Element.animate

document.getElementById("test").animate([
  { left: '0px' }, 
  { left: '50px' }
], {
  duration: 1000,
  fill: 'forwards'
});
#test {
  background-color: green;
  width: 100px;
  height: 100px;
  position: relative;
}
<div id="test"></div>

Upvotes: 2

Related Questions