Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically set css transform before transition

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/

like image 266
user1763510 Avatar asked Sep 27 '22 03:09

user1763510


1 Answers

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:

  • Use a small (but non zero) setTimeout to give some time for the browser to do its initial layout.
  • Force a browser layout by trying to access some property that require the browser to compute the page layout (e.g. document.body.offsetWidth).
  • Use 2 nested requestAnimationFrame's before applying your transform.

Demo: https://jsfiddle.net/fmt1rbsy/8/

like image 116
ghybs Avatar answered Oct 30 '22 21:10

ghybs