Tarrant Tarrant - 1 month ago 4
Javascript Question

Can't start and stop animation that runs in a constant loop

To simplify this question I have created two divs: when you click on the orange box the blue box below it will move back and forth in a continuous loop. What I want to be able to do is:


  • Click the orange box to start and STOP the blue box loop

  • After starting and stopping, the blue box will stop and continue each time where it left off.



I've tried just about everything and can't get it to work. Any advice would be greatly appreciated.



var hoverSlideBox = document.getElementById("hover_slide_box");
var slidingBox = document.getElementById("sliding_box");

hoverSlideBox.onclick = function() {
var pos = 0;
var moveLeft = false;
var stopAnimate = false;

init();

function init() {
setInterval(boxRight, 5);
}

function boxRight() {
if (!moveLeft) {
pos++;
slidingBox.style.left = pos + 'px';
}
if (pos == 500 || moveLeft) {
moveLeft = true;
boxLeft();
}
}

function boxLeft() {
if (moveLeft) {
pos--;
slidingBox.style.left = pos + 'px';
}
if (pos == 0 || !moveLeft) {
moveLeft = false;
}
}

}

<div id="hover_slide_box" style="background-color: #ff931e; cursor: pointer; position: absolute; height: 100px; width: 100px;"></div>
<div id="sliding_box" style="top: 120px; background-color: #0071bc; cursor: pointer; position: absolute; height: 100px; width: 100px;"></div>




Answer

You need to move some variables out of the onclick function so that they are not reset each time you click on the orange box. That, together with clearInterval, with give you a start/stop button.

var hoverSlideBox = document.getElementById("hover_slide_box");
var slidingBox = document.getElementById("sliding_box");
var running = false;
var intervalId;
var pos = 0;
var moveLeft = false;

hoverSlideBox.onclick = function() {

  init();

  function init() {
    if (!running) {
      intervalId = setInterval(boxRight, 5);
      running = true;
    } else {
      clearInterval(intervalId);
      running = false;
    }
  }

  function boxRight() {
    if (!moveLeft) {
      pos++;
      slidingBox.style.left = pos + 'px';
    }
    if (pos == 500 || moveLeft) {
      moveLeft = true;
      boxLeft();
    }
  }

  function boxLeft() {
    if (moveLeft) {
      pos--;
      slidingBox.style.left = pos + 'px';
    }
    if (pos == 0 || !moveLeft) {
      moveLeft = false;
    }
  }

}
<div id="hover_slide_box" style="background-color: #ff931e; cursor: pointer; position: absolute; height: 100px; width: 100px;"></div>
<div id="sliding_box" style="top: 120px; background-color: #0071bc; cursor: pointer; position: absolute; height: 100px; width: 100px;"></div>