0

I have this code:

var targetLocationX = 75;
var targetLocationY = 75;

var peice = $(".selected");
peice.css({
  "left": targetLocationX,
  "top": targetLocationY
});
img,
canvas {
  width: 75px;
  height: 75px;
  position: absolute;
  -webkit-user-drag: none;
}

img {
  left: 30px;
  top: 30px;
  background-color: rgba(0, 0, 0, 0);
  transition: left 0.2s, top 0.2s;
}
<img id="b-pawn-1" class="pawn bp selected" src="https://upload.wikimedia.org/wikipedia/commons/c/cd/Chess_pdt60.png">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>

The issue is that as I have specified the transition property in CSS, the image should animate to the target location, but unfortunately, this isn't the case. I have tried animating the image using transform, which works, but for my case, I prefer left and top.

Why is left not animating here?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
The Coding Fox
  • 1,488
  • 1
  • 4
  • 18
  • What's the `position` of the image you're trying to animate? By default it would be static so `left` and `top` would be ignored, but I don't see `position` in the CSS shown. Please update your question with a [mcve] demonstrating the problem, ideally a **runnable** one using Stack Snippets (the `[<>]` toolbar button); [here's how to do one](https://meta.stackoverflow.com/questions/358992/). – T.J. Crowder Sep 16 '22 at 14:54
  • Sorry for that, forgot to specify that. I have edited the question. – The Coding Fox Sep 16 '22 at 14:55
  • (Side note: "peice" should be spelled "piece," assuming it's the English word.) – T.J. Crowder Sep 16 '22 at 14:55
  • @T.J.Crowder Thanks for pointing that out. I've got the habit to spell peice like that. – The Coding Fox Sep 16 '22 at 14:56
  • The problem is repeating the `transition` property. As is usually (always?) the case with CSS, if you write the same property more than once, the last one wins. To animate two properties, use a comma-separated list of transitions: `transition: left 0.2s, top: 0.2s`. – T.J. Crowder Sep 16 '22 at 14:59
  • @T.J.Crowder I tried it. Still no luck... – The Coding Fox Sep 16 '22 at 15:01
  • 1
    [Works for me](https://jsfiddle.net/tjcrowder/hpLu36ty/). That's a copy-and-paste of your code with missing bits added (edit: your code before you added the missing bits), updating `transition` to use a comma-separated list. – T.J. Crowder Sep 16 '22 at 15:03
  • I've completely edited the question. – The Coding Fox Sep 16 '22 at 15:05
  • 1
    The latest edited snippet, with the comma-delimited list, works. – T.J. Crowder Sep 16 '22 at 15:06
  • @T.J.Crowder saw your link. But can't achieve the same effect, due to some reason. Should do even more debugging I guess. Even a copy paste is not working. – The Coding Fox Sep 16 '22 at 15:08
  • 1
    The latest snippet in your question works. – T.J. Crowder Sep 16 '22 at 15:09

0 Answers0