Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why transition does not work on first click event?

Tags:

javascript

I try to move a div(#ball) inside another the div(#square) to click point by Javascript. The first click would move #ball without transition duration 1s. But from second click things work normally until I refresh the Html page.

I use a new Chrome browser.

Html

<div class="" id="square">
    <div class="" id="ball" ></div>
</div>

CSS

#square {
  /*background-color, width etc */
  position: relative;
}

#ball {
  /*background-color, width etc */
   position: absolute;
   transition-duration: 1s;
}

Javascript

let square = document.getElementById('square');
let ball = document.getElementById('ball');

square.addEventListener('click', (event) => {
    ball.style.top = event.pageY + "px";
    ball.style.left = event.pageX + "px";  
});
like image 323
Vo Phu Avatar asked Dec 18 '25 22:12

Vo Phu


1 Answers

Without specifying a top and left for the #ball element, they default to auto

Now, when transitioning from auto => 100 for example, there is no transition happening since auto is not a number

Specifying an initial top and left left will make this work

let square = document.getElementById('square');
let ball = document.getElementById('ball');

square.addEventListener('click', (event) => {
  ball.style.top = event.pageY + "px";
  ball.style.left = event.pageX + "px";
});
#square {
  background-color: grey;
  width:90%;
  height:90vh;
  position: relative
}

#ball {
  background-color:blue;
  width:20px;
  height:20px;
  top:0;
  left:0;
  position: absolute;
  transition-duration: 1s;
}
<div class="" id="square">
  <div class="" id="ball"></div>
</div>
like image 115
Bravo Avatar answered Dec 21 '25 14:12

Bravo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!