Demo of Image moving vertically between two limits

Click Start to move the image vertically between the top and bottom 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 maxTop = Math.max(0, area.clientHeight - image.offsetHeight);
    let top = image.offsetTop + (2 * direction);
    if (top >= maxTop) { top = maxTop; direction = -1; }
    if (top <= 0) { top = 0; direction = 1; }
    image.style.top = `${top}px`;
    output.textContent = `X: ${image.offsetLeft} Y: ${top}`;
    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>