Add elements to circle
Dynamically add and remove elements in a circular layout
HTML
<body>
<ul id="list"></ul>
<button id="add-item">Add item</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</body>
CSS
#list{
background-color: blue;
height: 400px;
width: 400px;
border-radius: 50%;
position: relative;
}
.list-item{
list-style: none;
background-color: red;
height: 50px;
width: 50px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -25px;
margin-top: -25px;
}
JavaScript
var list = $("#list");
var zero_start = 270 // if you want to start from a different position, should be positive
var updateLayout = function(listItems){
var offsetAngle = (180 / (listItems.length-1));
for(var i = 0; i < listItems.length; i ++){
var rotateAngle = zero_start + (offsetAngle * i || 0);
$(listItems[i]).css("transform", "rotate(" + rotateAngle + "deg) translate(0, -200px) rotate(-" + rotateAngle + "deg)")
};
};
$(document).on("click", "#add-item", function(){
var listItem = $("<li class='list-item'>Things go here<button class='remove-item'>Remove</button></li>");
list.append(listItem);
var listItems = $(".list-item");
updateLayout(listItems);
});
$(document).on("click", ".remove-item", function(){
$(this).parent().remove();
var listItems = $(".list-item");
updateLayout(listItems);
});