I am trying to simulate a mouse animation. I would like to dynamically set the position, then move it with a css transition. So far I am able to get a program that moves the mouse. However, I am having trouble setting the initial position dynamically with javascript. My code looks like this:
Here is the CSS
.cursorDiv {
width: 30px;
height: 30px;
transform: translate(0px,0px);
transition: 2s ease;
}
.cursorDivMoved {
transform: translate(100px,200px);
}
Here is the javascript:
var cursorDiv = document.createElement("img");
cursorDiv.className = "cursorDiv";
cursorDiv.src="https://cdn2.iconfinder.com/data/icons/windows-8-metro- style/512/cursor.png";
document.body.appendChild(cursorDiv);
setTimeout(function() {
$(".cursorDiv").toggleClass("cursorDivMoved");
}, 1000);
//cursorDiv.style.transform="translate(100px,50px)";
When I run this it works fine. However, when I try to change the initial position with javascript (uncomment last line), then the transition doesn't occur anymore.
Here is a Demo:
https://jsfiddle.net/fmt1rbsy/5/
If you programmatically set the style.transform
property directly on your element (which you need if you want to move it to an arbitrary position through JS), it will override any transform
specified in classes. Hence adding "cursorDivMoved"
class later on does not transform (translate / move) it.
You have to continue moving it by specifying its style.transform
property, or simply remove it: cursorDiv.style.transform = null
Demo: https://jsfiddle.net/fmt1rbsy/9/
You may also want to have the very first translate
being transitioned. In that case, you have to wait for the browser to make an initial layout with your element at its start position, otherwise it will see no transition (it will see it directly after the transform is applied, i.e. at its final position). You can either:
setTimeout
to give some time for the browser to do its initial layout.document.body.offsetWidth
).requestAnimationFrame
's before applying your transform
.Demo: https://jsfiddle.net/fmt1rbsy/8/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With