Aman Sadhwani
Aman Sadhwani

Reputation: 3658

How to change value of keyframe dynamically?

I have the following code to move an image

@-webkit-keyframes mymove {
  from {left: 0px;}
  to {left: 40%;}
}

Now I need to change the value of left ie 40% using javascript how do i achieve this ?

Upvotes: 1

Views: 1458

Answers (2)

Amit
Amit

Reputation: 1560

You can use jquery animate function for transition of the div element. check the below example:

$(document).ready(function(){
  $("#box").click(function(){
    $("#box").animate({
        left: '40%'
    });
  });
});
#box {
  background: #98bf21;
  height: 100px;
  width: 100px;
  position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
</head>
<body>

<div id="box"></div>

</body>
</html>

Upvotes: 0

Hao Wu
Hao Wu

Reputation: 20669

Here's the reference for using transition:

document.querySelector('.box').addEventListener('click', function() {
   // set the left value dynamically
   this.style.left = '40%';
});
/* cosmetics, ignore these */
.box {
  width: 100px;
  height: 100px;
  background-color: salmon;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
}

/* relevent styles */
.box {
  position: absolute;
  left: 0;
  transition: left 0.5s;
}
<div class="box">click me</div>

Upvotes: 1

Related Questions