Add elements to circle
Dynamically add and remove elements in a circular layout
by skwidbreth
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%;
}
JavaScript
var list = $("#list");
var updateLayout = function(listItems){
for(var i = 0; i < listItems.length; i ++){
var offsetAngle = 360 / listItems.length;
var rotateAngle = offsetAngle * i;
$(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);
});