badbye badbye - 4 months ago 8
CSS Question

Change css to the element which has animation?

I have a css animation set up for a image as shown below:

<style>
#egg{

height:50px;
z-index: 2;

margin-left:950px;
margin-top: 450px;
position:absolute;
animation-duration: 6.4s;
animation-name: slide;
animation-iteration-count: infinite;
}
@keyframes slide{
0% {
margin-left: 910px;
}

49.99% {
-moz-transform: scaleX(1);
-o-transform: scaleX(1);
-webkit-transform: scaleX(1);
transform: scaleX(1);
filter: FlipH;
-ms-filter: "FlipH";
}
50%{
margin-left: 1250px;

-moz-transform: scaleX(-1);
-o-transform: scaleX(-1);
-webkit-transform: scaleX(-1);
transform: scaleX(-1);
filter: FlipH;
-ms-filter: "FlipH";
}
100%{
margin-left:910px;
-moz-transform: scaleX(-1);
-o-transform: scaleX(-1);
-webkit-transform: scaleX(-1);
transform: scaleX(-1);
filter: FlipH;
-ms-filter: "FlipH";
}
}
</style>


Normally I use the code below to change the css of the element:

$(element).css('margin-left','+=1000px');


But this is not working anymore for the element with animation. So I wondered how to change css margin to the element has animation attached?

The reason I'm doing this that when a button is clicked, the element should be show up in the middle of screen to start animation. but using margin:x% will damage the animation, sos I need to detect the window height and width thus adjust the margin dynamically.

Answer

You can parse current integer value and then add to it what you want:

$(document).ready(function() {
  var element = $("#change-margin");
  setTimeout(function() {
    var current = parseInt(element.css('margin-left'));
    element.css('margin-left', 100 + current);
  }, 1000);
});
#change-margin {
  margin-left: 20px;
  width: 50px;
  height: 50px;
  background-color: #fea;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="change-margin"></div>