The original page called this a random movement demo, but its actual behavior is diagonal movement that reverses at four boundaries. This modernization preserves that visible behavior and makes the boundaries responsive.
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 dx = 2;
let dy = 2;
function draw() {
const maxLeft = Math.max(0, area.clientWidth - image.offsetWidth);
const maxTop = Math.max(0, area.clientHeight - image.offsetHeight);
let left = image.offsetLeft + dx;
let top = image.offsetTop + dy;
if (left >= maxLeft || left <= 0) { dx = -dx; left = Math.min(maxLeft, Math.max(0, left)); }
if (top >= maxTop || top <= 0) { dy = -dy; top = Math.min(maxTop, Math.max(0, top)); }
image.style.left = `${left}px`;
image.style.top = `${top}px`;
output.textContent = `X: ${left} Y: ${top}`;
animationId = requestAnimationFrame(draw);
}
function start() { if (animationId === null) animationId = requestAnimationFrame(draw); }
function reset() {
if (animationId !== null) cancelAnimationFrame(animationId);
animationId = null; dx = 2; dy = 2;
image.style.left = '40px'; image.style.top = '40px'; output.textContent = '';
}
startButton.addEventListener('click', start);
resetButton.addEventListener('click', reset);
<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>