1

I try to assign "{transform: 'translateX(5px)'}" to a variable (called 'aa'). In order to add the pixel value of movement everytime a keydown function being triggered. But it won't work. Why?

I've tried something like this with: css()method and offset()method, they're all work, but why with this animate()method it didn't work?

<!DOCTYPE html>
<html>

<head>
<style>
    div.divx {
        width: 50px;
        height: 50px;
        background-color: black;
        position: absolute;
        left: 15px;
        top: 15px;
        z-index: -1;
    }
</style>
</head>

<body>
<div class="divx"></div>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
    $(document).ready(function() {
        var i = 0;
        $(window).keydown(function(e) {

            if (e.which == 39) { //39 is right button
                i += 5;
                a = i + 'px';
                yy = 'translateX(' + a + ')';
                xx = '"' + yy + '"';
                aa = "{transform: " + xx + "}";
                alert(aa);
                $(".divx").animate(aa);
            }
        })

    })
</script>
</body>

</html>
Yogeshree Koyani
  • 1,649
  • 10
  • 19
Hudoyo Danumurti
  • 75
  • 1
  • 3
  • 9

1 Answers1

2

aa appear to be String , .animate() expects Object

but it work on alert..

Yes, alerts String . Try using css transition , pass string to .css()

<!DOCTYPE html>
<html>

<head>
  <style>
    div.divx {
      width: 50px;
      height: 50px;
      background-color: black;
      position: absolute;
      left: 15px;
      top: 15px;
      z-index: -1;
      transition: transform 500ms;
    }
  </style>
</head>
<body>
  <div class="divx"></div>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
  </script>
  <script>
    $(document).ready(function() {
      var i = 0, a, yy, aa;
      $(window).keydown(function(e) {
        if (e.which == 39) { //39 is right button
          i += 5;
          a = i + 'px';
          yy = 'translateX(' + a + ')';
          aa = "transform," + yy;
          $(".divx").css("transform", yy);
        }
      })
    })
  </script>
</body>

</html>
guest271314
  • 1
  • 15
  • 104
  • 177