Demo of Image moving horizontally between two limits

Click Start to move the image horizontally between the left and right boundaries. Reset stops the animation and returns it to the starting point.

Help icon used in JavaScript image movement demo
Return to tutorial on Moving image across screen Moving image vertically within two boundaries Moving image horizontally within two boundaries Moving image randomly within four boundaries Moving image by using up, down, left & right keys

JavaScript source

const image = document.getElementById('i1');
const area = document.getElementById('move-area');
const output = document.getElementById('msg');
const startButton = document.getElementById('start');
const resetButton = document.getElementById('reset');
let animationId = null;
let direction = 1;
let lastTime = 0;

function draw(time) {
  if (!lastTime) lastTime = time;
  const elapsed = time - lastTime;
  if (elapsed >= 10) {
    const maxLeft = Math.max(0, area.clientWidth - image.offsetWidth);
    let left = image.offsetLeft + (2 * direction);
    if (left >= maxLeft) { left = maxLeft; direction = -1; }
    if (left <= 0) { left = 0; direction = 1; }
    image.style.left = `${left}px`;
    output.textContent = `X: ${left} Y: ${image.offsetTop}`;
    lastTime = time;
  }
  animationId = requestAnimationFrame(draw);
}

function start() {
  if (animationId !== null) return;
  lastTime = 0;
  animationId = requestAnimationFrame(draw);
}

function reset() {
  if (animationId !== null) cancelAnimationFrame(animationId);
  animationId = null;
  direction = 1;
  image.style.left = '40px';
  image.style.top = '40px';
  output.textContent = '';
}
startButton.addEventListener('click', start);
resetButton.addEventListener('click', reset);

HTML source

<div id="move-area" class="border rounded mb-3" style="position:relative; min-height:420px; overflow:hidden; touch-action:none;">
  <img src="images/help.jpg" id="i1" alt="Help icon used in JavaScript image movement demo" style="position:absolute; left:40px; top:40px; max-width:80px; height:auto;">
</div>
<button type="button" id="start">Start</button>
<button type="button" id="reset">Reset</button>
<div id="msg"></div>