Demo of Image moving by up, down, left and right arrow keys

Focus this page and use the keyboard arrow keys. The original keyboard facility is preserved, but the modern code uses event.key instead of legacy window.event.keyCode.

Help icon used in JavaScript image movement demo

Use left, right, up and down arrow keys to move the image.

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 step = 10;

function moveByKey(key) {
  let left = image.offsetLeft;
  let top = image.offsetTop;
  const maxLeft = Math.max(0, area.clientWidth - image.offsetWidth);
  const maxTop = Math.max(0, area.clientHeight - image.offsetHeight);

  switch (key) {
    case 'ArrowLeft': left -= step; break;
    case 'ArrowRight': left += step; break;
    case 'ArrowUp': top -= step; break;
    case 'ArrowDown': top += step; break;
    default: return;
  }
  image.style.left = `${Math.min(maxLeft, Math.max(0, left))}px`;
  image.style.top = `${Math.min(maxTop, Math.max(0, top))}px`;
  output.textContent = `X: ${image.offsetLeft} Y: ${image.offsetTop}`;
}

document.addEventListener('keydown', (event) => {
  if (event.key.startsWith('Arrow')) {
    event.preventDefault();
    moveByKey(event.key);
  }
});

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:80px; max-width:80px; height:auto;">
</div>
<div id="msg"></div>
<p>Use left, right, up and down arrow keys to move the image.</p>