Circle move to position when I clicked
<!DOCTYPE html>
<html>
<head>
<title>Circle Moves When Clicked</title>
<style>
body {
margin: 0;
overflow: hidden;
height: 100vh;
}
#circle {
position: absolute;
width: 50px;
height: 50px;
background-color: blue;
border-radius: 50%;
transform: translate(-50%, -50%);
transition: all 0.5s ease;
cursor: pointer;
}
</style>
</head>
<body>
<div id="circle"></div>
<script>
const circle = document.getElementById('circle');
// Initial position (center of screen)
let posX = window.innerWidth / 2;
let posY = window.innerHeight / 2;
// Set initial position
circle.style.left = posX + 'px';
circle.style.top = posY + 'px';
// Move circle only when clicking on the circle
circle.addEventListener('click', (event) => {
// Prevent the click from bubbling up to document
event.stopPropagation();
// Function to handle document click
const moveCircle = (e) => {
posX = e.clientX;
posY = e.clientY;
circle.style.left = posX + 'px';
circle.style.top = posY + 'px';
// Remove this listener after moving
document.removeEventListener('click', moveCircle);
};
// Listen for the next click anywhere to move the circle
document.addEventListener('click', moveCircle);
});
</script>
</body>
</html>
Code 2
<!DOCTYPE html>
<html>
<head>
<title>Two Moving Circles</title>
<style>
body {
margin: 0;
overflow: hidden;
height: 100vh;
}
.circle {
position: absolute;
width: 50px;
height: 50px;
border-radius: 50%;
transform: translate(-50%, -50%);
transition: all 0.5s ease;
cursor: pointer;
}
#blueCircle {
background-color: blue;
}
#redCircle {
background-color: red;
}
</style>
</head>
<body>
<div id="blueCircle" class="circle"></div>
<div id="redCircle" class="circle"></div>
<script>
// Initialize both circles
const blueCircle = document.getElementById('blueCircle');
const redCircle = document.getElementById('redCircle');
// Position blue circle on left
let blueX = window.innerWidth / 3;
let blueY = window.innerHeight / 2;
blueCircle.style.left = blueX + 'px';
blueCircle.style.top = blueY + 'px';
// Position red circle on right
let redX = window.innerWidth * 2/3;
let redY = window.innerHeight / 2;
redCircle.style.left = redX + 'px';
redCircle.style.top = redY + 'px';
// Function to handle circle movement
function setupCircleMovement(circle, x, y) {
circle.addEventListener('click', (event) => {
event.stopPropagation();
const moveCircle = (e) => {
x = e.clientX;
y = e.clientY;
circle.style.left = x + 'px';
circle.style.top = y + 'px';
document.removeEventListener('click', moveCircle);
};
document.addEventListener('click', moveCircle);
});
// Return the position variables so they can be updated
return { x, y };
}
// Set up movement for both circles
const bluePos = setupCircleMovement(blueCircle, blueX, blueY);
const redPos = setupCircleMovement(redCircle, redX, redY);
</script>
</body>
</html>
Comments
Post a Comment