I'm attempting to randomly display 6 letters from the list letters
in a circle. Currently I've adapted code that displays 6 divs with the class .field
and provides a number (0-5) as an attribute to each field
.
I'd like to randomly assign and display each letter (without repeating) within each field. However, I'm unsure about how to identify and splice into the list of fields (although I'm also unsure if splicing is the way to go). Does anyone have advice?
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<meta charset="utf-8">
<title></title>
</head>
<style media="screen">
body {
padding: 2em;
}
#container {
width: 600px;
height: 600px;
border: 2px solid blue;
position: relative;
}
.field {
width: 100px;
height: 100px;
position: absolute;
border: 2px solid #f00;
}
.field:hover {
border: 2px solid blue;
}
#crosshair-x {
width: 100px;
height: 2px;
background: #000;
position: absolute;
right: 250px;
top: 300px;
}
#crosshair-y {
width: 2px;
height: 100px;
background: #000;
position: absolute;
left: 300px;
top: 250px;
}
</style>
<body>
Num: <input type="text" value="6" />
<div id="container">
<div id="center"></div>
<div id="crosshair-x"></div>
<div id="crosshair-y"></div>
</div>
</body>
<script type="text/javascript">
function createFields() {
var num = Math.floor(Math.random() * 6) + 1
$('.field').remove();
var container = $('#container');
for (var i = 0; i <
+$('input:text').val(); i++) {
$('<div />', {
'class': 'field',
'attribute': i,
'text': i,
}).appendTo(container);
}
}
function distributeFields() {
var ang = Math.floor(Math.random() * 360) + 0
var radius = 200;
var fields = $('.field'),
container = $('#container'),
width = container.width(),
height = container.height(),
angle = ang,
step = (2 * Math.PI) / fields.length;
fields.each(function() {
var x = Math.round(width / 2 + radius * Math.cos(angle) - $(this).width() / 2);
var y = Math.round(height / 2 + radius * Math.sin(angle) - $(this).height() / 2);
if (window.console) {
console.log($(this).text(), x, y);
}
$(this).css({
left: x + 'px',
top: y + 'px'
});
angle += step;
});
}
$('input').change(function() {
createFields();
distributeFields();
});
createFields();
distributeFields();
letters = ["A","B","C","D","E","F"]
</script>
</html>
I've adapted this code from @ThiefMaster (thank you!): Dynamically arrange some elements around a circle