skip to Main Content
</head>
<body>
<script>
var temp;
document.addEventListener("click",(function(e) {
    temp=document.createElement("img")
    temp.src="https://images.freeimages.com/images/large-previews/82d/eastern-rosella-1-1617233.jpg"
    temp.style+="left:0; top:0;"
    temp.style.position+="absolute"
    temp.height="200"
    temp.width="200"
    temp.style.left=e.clientX
    temp.style.top=e.clientY
    temp.style.transition="all 2s"
    document.body.append(temp)
    temp.style.transform="translate(0px, 50px)"
}))
</script>
</body>

This piece of code is meant to create an image at the user’s mouse click, that will move it down by 50px, with a transition duration of 2s. However, it seems to ignore the transition property, and teleport down 50px instead without the animation.

I have also added ease 2s to see if the translation of 50px would be delayed by 2 secs, but it ignored that.

I have also tried using transform+= instead of transform=, if that would do anything, but it didn’t.

This is the created element:

<img src="https://images.freeimages.com/images/large-previews/82d/eastern-rosella-1-1617233.jpg" height="200" width="200" style="top: 316px; position: absolute; left: 849px; transition: all 2s; transform: translate(0px, 50px);">

The transition property is as it should be, but it has no effect.

How do I make the image element move smoothly, instead of changing position?

2

Answers


  1. Add an img.style.transform to the img.onload event:

    document.addEventListener('click', event =>  {
      const img = document.createElement('img');
      img.src = 'https://images.freeimages.com/images/large-previews/82d/eastern-rosella-1-1617233.jpg';
      img.style.cssText = `
        left: ${event.clientX}px;
        top: ${event.clientY}px;
        position: absolute;
        width: 200px;
        height: 200px;
        transition: 2s;
      `;
      document.body.append(img)
      img.onload = () => img.style.transform = 'translateY(50px)';
    })
    Login or Signup to reply.
  2. This code give you ability to move the image independently to where you click.

    const f = document.getElementById("img");
    document.addEventListener(
      "click",
      (ev) => {
        f.style.transform = `translateY(${ev.clientY - 25}px)`;
        f.style.transform += `translateX(${ev.clientX - 25}px)`;
      },
      false,
    );
    img {
      width: 35%;
      transition: all 2s;
    }
      <img id="img" src="https://images.freeimages.com/images/large-previews/82d/eastern-rosella-1-1617233.jpg">

    If you want it to always move to 50px below, then just change the js to this code below.

    const f = document.getElementById("img");
    document.addEventListener(
      "click",
      (ev) => {
        f.style.transform = `translateY(50px)`;
        f.style.transform += `translateX(0)`;
      },
      false,
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search