2

TranslateX is not working for me in JQuery. I would like to use .animate() method instead of .css().

JavaScript

$(".test").hover(function() {
    $(this).animate({'transform': 'translateX(100%);'}, 1000);
});

CSS

.test {
  background-color: #f9333c;
  width: 100%;
  height: 100%;
  transform: translateX(0%);
}
Maistrenko Vitalii
  • 994
  • 1
  • 8
  • 16
kabugh
  • 305
  • 1
  • 9
  • 30
  • which browser do you test this? Is it possible that you are testing this in a non webkit browser? try also to use this: `-webkit-transform` – Rotan075 Mar 29 '18 at 12:20
  • @Rotan075 `transform` hasn't required browser prefixes for around 4 years. – Turnip Mar 29 '18 at 12:55
  • @Turnip oh never thought about that. I always used it just to be sure. Thanks everyday we learn something new isn't it ;) – Rotan075 Mar 29 '18 at 13:00
  • jquery animate method not support transform so you need to use css method – Pankaj Bisht Mar 29 '18 at 13:25
  • @Turnip it needs vendor prefix for mobile https://developer.mozilla.org/en-US/docs/Web/CSS/transform – Huangism Mar 29 '18 at 15:03

1 Answers1

3

Here is a fiddle using animate. I've added some code comments to walk you through what's going on.

HTML:

<h1 class="test">test</h1>

JavaScript:

//Get the element you want to animate
var testElement = $('.test');

function run(v){
  //Reverse the array
  var reversed = JSON.parse(JSON.stringify(v)).reverse();

  $(v[0]).animate(v[1], {
      //The speed the element moves - lower is faster
      duration: 500,
      step: function(val) {
          //Adding the transform to your element
          testElement.css("transform", `translateX(${val}px)`); 
      },
      done: function(){
          //Re-running the function but in reverse with the reverse we did above
          run(reversed)
      }
  })
};

//Calling our function and passing in the parameters
run([{y:0}, {y:100}])

You'll need to play around with the values you pass into run().

There is a similar answer here that show's how this is done with translateY, however I found the code a bit hard to grasp at first glance so I've dissected it a bit and made it work for your scenario with translateX.

maxshuty
  • 9,708
  • 13
  • 64
  • 77