RIM
RIM

Reputation: 19

Animating with setInterval in JavaScript

The question is how to get the train to return to the initial position by the second click.

Animation in this case is drawn from 0 to 400px in the left. I need a second click to draw from 400px to 0, so the train returns to its original position.

And why in this animation the train does not always matter in 400px, and how we achieve accuracy when using this function.

train.onclick = function() {
  var start = Date.now(); // сохранить время начала

  var timer = setInterval(function() {
    // вычислить сколько времени прошло из opts.duration
    var timePassed = Date.now() - start;

    train.style.left = timePassed / 5 + 'px';

    if (timePassed > 2000) clearInterval(timer);

  }, 20);
}
#train {
  position: relative;
  cursor: pointer;
}
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
  <img id="train" src="https://js.cx/clipart/train.gif">
</body>
</html>

Upvotes: 0

Views: 113

Answers (2)

Lam Pham
Lam Pham

Reputation: 58

I modify your code and the code below works well:

window.onload = function() {
var train = document.getElementById("train");
var isLeftToRight = 0;
var startPosition = 0;

train.onclick = function() {
    isLeftToRight = 1 - isLeftToRight;
    var start = Date.now(); // сохранить время начала

    var timer = setInterval(function() {
    // вычислить сколько времени прошло из opts.duration
    var timePassed = Date.now() - start;
    if(isLeftToRight) train.style.left = timePassed / 5 + 'px';
    else train.style.left = (startPosition - timePassed / 5) + 'px';

    if (timePassed > 2000) {
        clearInterval(timer);
        startPosition = timePassed / 5;
    }
  }, 20);
}

Upvotes: 1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

The best thing about the new CSS spec is that you can leave all these things to CSS and use JavaScript purely for interaction. For example, the best way to do this is:

document.getElementById("train").onclick = function() {
  this.classList.toggle("end");
}

The above is the only JavaScript you need. Rest all magic is done by CSS. The good part about this is, it uses GPU, which is more efficient than CPU. See the snippet:

document.getElementById("train").onclick = function() {
  this.classList.toggle("end");
}
#train {
  position: relative;
  left: 0;
  cursor: pointer;
  -webkit-transition: left 2s; /* Safari */
  transition: left 2s;
}
#train.end {
  left: 400px;
}
<img id="train" src="https://js.cx/clipart/train.gif" />

For browser support, see Can I use?

Upvotes: 1

Related Questions