Shinji
Shinji

Reputation: 101

CSS animation. transition applies to all the other times, but not the first time

I'm trying to make a sample where when the user click on the window, the circle (div) will move to that place with a transition. However, it does not work on the first click, but all the others. So I wonder what's making it do that.

<!doctype html>
<html>
<head>
<title>Hover</title>
<meta charset="UTF-8">

<link rel="stylesheet" type="text/css" href="CSS/mystyles.css" >

</head>
<body>
<div id = "divGroup" class = 'group'>
</div>
<script src="JS/code.js"></script>
</body>
</html>

the javascript (i'm using javascript to receive the values and define new values:

var divGroup = document.getElementById("divGroup");

window.onclick = function(evt) {
divGroup.style.left = (evt.clientX - 25) + "px";
divGroup.style.top = (evt.clientY - 25) + "px";
}

the css:

#divGroup {
width: 50px;
height:50px;
background-color:lightblue;
border-radius:50%;
position: absolute;
transition: all 0.5s;
}

Upvotes: 0

Views: 32

Answers (1)

t1m0n
t1m0n

Reputation: 3431

You should add initial left and top values in css for #divGroup

var divGroup = document.getElementById("divGroup");

window.onclick = function(evt) {
  divGroup.style.left = (evt.clientX - 25) + "px";
  divGroup.style.top = (evt.clientY - 25) + "px";
}
#divGroup {
  width: 50px;
  height: 50px;
  background-color: lightblue;
  border-radius: 50%;
  position: absolute;
  transition: all 0.5s;
  left: 0;
  top: 0;
}
<div id="divGroup" class='group'>

Upvotes: 4

Related Questions