Code (ready to copy-paste):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Click the Ball</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: system-ui;
background: #ffffff;
height: 100vh;
overflow: hidden;
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-start;
padding-top: 40px;
}
h1 {
font-size: 1.6rem;
font-weight: 700;
margin-bottom: 12px;
text-align: center;
user-select: none;
}
.ball {
position: absolute;
width: 60px;
height: 60px;
background: #000000;
border-radius: 50%;
cursor: pointer;
transition: left 0.4s ease, top 0.4s ease;
box-shadow: 0 4px 20px rgba(0,0,0,0.25);
}
.ball:hover { transform: scale(1.08); }
</style>
</head>
<body>
<h1>Click the ball, it moves!</h1>
<div class="ball" id="ball"></div>
<script>
const Ball = document.getElementById('ball');
const BallSize = 60;
function GetSafePosition() {
const WindowWidth = window.innerWidth;
const WindowHeight = window.innerHeight;
const PositionX = Math.random() * (WindowWidth - BallSize);
const PositionY = Math.random() * (WindowHeight - BallSize - 120) + 100;
return { PositionX, PositionY };
}
function MoveBallToRandomPosition() {
const RandomPosition = GetSafePosition();
Ball.style.left = RandomPosition.PositionX + 'px';
Ball.style.top = RandomPosition.PositionY + 'px';
}
function ClampBallWithinWindow() {
const WindowWidth = window.innerWidth;
const WindowHeight = window.innerHeight;
let LeftOffset = parseFloat(Ball.style.left) || WindowWidth / 2 - BallSize / 2;
let TopOffset = parseFloat(Ball.style.top) || WindowHeight / 2 - BallSize / 2;
LeftOffset = Math.max(0, Math.min(LeftOffset, WindowWidth - BallSize));
TopOffset = Math.max(100, Math.min(TopOffset, WindowHeight - BallSize - 20));
Ball.style.left = LeftOffset + 'px';
Ball.style.top = TopOffset + 'px';
}
Ball.style.left = (window.innerWidth / 2 - BallSize / 2) + 'px';
Ball.style.top = (window.innerHeight / 2 - BallSize / 2) + 'px';
Ball.addEventListener('click', MoveBallToRandomPosition);
window.addEventListener('resize', ClampBallWithinWindow);
</script>
</body>
</html>