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.
Use left, right, up and down arrow keys to move the image.
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);
}
});
<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>