I have a CSS element/ball which I am moving to new coordinates on click.
This works, however the transition I am applying does not seem to take affect.
The ball jumps to the new location. I want it to slowly animate/transition/move to the new coordinates.
What am I doing wrong?
.ball {
width: 30px;
height: 30px;
border-radius: 50%;
background-color: #FF5722;
position: absolute;
// d.style.transition = "all 1s ease-in";
transition: all 3s ease-in-out;
// -webkit-transition: all 1s ease-in-out;
// -moz-transition: all 1s ease-in-out;
// -o-transition: all 1s ease-in-out;
// -ms-transition: all 1s ease-in-out;
}
handleClick = (e) => {
console.log('ball clicked');
var d = document.getElementById('ball');
console.log('d', d);
d.style.x = 12 + "px";
d.style.top = 341 + "px";
d.style.transition = "all 1s ease-in";
}
Thanks
It seems like there are a few things that need to be corrected;
.ball
class in your CSS where as the ball element is being accessed via an id, which suggests a potential problem. Is the ball
class being applied to the element with id ball
?x
property on the style object should be replaced with the left
property to ensure horizontal movement of the ball elementHere's an example demonstrating these corrections:
const handleClick = (e) => {
console.log('ball clicked');
const ball = document.getElementById('ball');
/* Setting random coordinates to demonstrate transition */
ball.style.left = Number.parseInt(Math.random() * 200) + "px";
ball.style.top = Number.parseInt(Math.random() * 200) + "px";
}
document.addEventListener("click", handleClick);
#field {
position: relative;
width: 100%;
height: 100%;
}
/* Corrected to id selector with # rather than class selector
with . */
#ball {
position: absolute;
width: 30px;
height: 30px;
border-radius: 50%;
background-color: #FF5722;
position: absolute;
/* Assigning transition behavior which is applied during
property changes */
transition: all 3s ease-in-out;
}
<div id="field">
<div id="ball"></div>
</div>
Hope that helps