Issue with JavaScript causing circles to form around a parent div

I am struggling to position a set of circles around a parent div in my code. I want 6 circles to form a circle around the parent div, but they are not lining up correctly. Can someone help me identify what I'm doing wrong?

var div = 360 / 6;
var radius = 150;
var parentdiv = document.getElementById('parentdiv');
var offsetToParentCenter = parseInt(parentdiv.offsetWidth / 2); //assumes parent is square
var offsetToChildCenter = 20;
var totalOffset = offsetToParentCenter - offsetToChildCenter;
var elementList = document.querySelectorAll(".circle");
for (var i = 0; i <= elementList.length; i++) {
  elementList[i].style.position = 'absolute';
  var y = Math.sin((div * i) * (Math.PI / 180)) * radius;
  var x = Math.cos((div * i) * (Math.PI / 180)) * radius;
  elementList[i].style.top = (y + totalOffset).toString() + "px";
  elementList[i].style.left = (x + totalOffset).toString() + "px";
}
.container label {
  cursor: pointer;
  height: 150px;
  width: 150px;
  display: table-cell;
  text-align: center;
  padding: 20px 10px 10px 20px;
  vertical-align: middle;
  border-radius: 50%;
  background: green;
}

.container input[type="checkbox"] {
  display: none;
}

#parentdiv {
  position: relative;
  width: 150px;
  height: 150px;
  background-color: #ac5;
  border-radius: 150px;
  margin: 150px;
}

.div2 {
  position: absolute;
  width: 40px;
  height: 40px;
  background-color: #ac5;
  border-radius: 100px;
}
<div id="parentdiv"></div>
<div class="container">
  <input type="checkbox" id="test1">
  <div class="circle">
    <label for="test1" class="inner">Test 1</label>
  </div>
  <input type="checkbox" id="test2">
  <div class="circle">
    <label for="test2" class="inner">Test 2</label>
  </div>
  <input type="checkbox" id="test3">
  <div class="circle">
    <label for="test3" class="inner">Test 3</label>
  </div>
  <input type="checkbox" id="test4">
  <div class="circle">
    <label for="test4" class="inner">Test 4</label>
  </div>
  <input type="checkbox" id="test5">
  <div class="circle">
    <label for="test5" class="inner">Test 5</label>
  </div>
  <input type="checkbox" id="test6">
  <div class="circle">
    <label for="test6" class="inner">Test 6</label>
  </div>
</div>

JSFiddle Demo

Answer №1

Upon reviewing your code, I noticed a few doubts that arose:

  1. What is the purpose of using padding in the container class? - It seems like this may cause the children circles to appear larger than the parent circle. If you are dividing 360 degrees among the number of children (6), then all the circles could have the same dimensions as the parent circle.
  2. Why set var offsetToChildCenter = 20;? - Assuming the container class has attributes "height: 150px; width: 150px;", then changing this line to var offsetToChildCenter = 75 might be more appropriate.
  3. What's the rationale behind subtracting offsetToChildCenter from offsetToParentCenter (var totalOffset = offsetToParentCenter - offsetToChildCenter;)? - Perhaps considering changing it to var totalOffset = offsetToParentCenter + offsetToChildCenter; would make more sense.

Based on these adjustments, the revised source code will look like:

.container label {
  cursor: pointer;
  height: 150px;
  width: 150px;
  display: table-cell;
  text-align: center;
  vertical-align: middle;
  border-radius: 50%;
  background: green;
}

Javascript:

var div = 360 / 6;
var radius = 150;
var parentdiv = document.getElementById('parentdiv');
var offsetToParentCenter = parseInt(parentdiv.offsetWidth / 2); //assuming parent is square
var offsetToChildCenter = 75;
var totalOffset = offsetToParentCenter + offsetToChildCenter;
var elementList = document.querySelectorAll(".circle");
for (var i = 0; i <= elementList.length; i++) {
  elementList[i].style.position = 'absolute';
  var y = Math.sin((div * i) * (Math.PI / 180)) * radius;
  var x = Math.cos((div * i) * (Math.PI / 180)) * radius;
  elementList[i].style.top = (y + totalOffset).toString() + "px";
  elementList[i].style.left = (x + totalOffset).toString() + "px";
}


Ultimately, even with these adjustments, the children circles may not align perfectly with the parent circle due to potential rounding errors stemming from the IEEE-754 double format ().

Answer №2

The margin on your main div appears to be misaligned. I suggest making the "mainDiv" a nested element within the container for better structure. If it's not serving as a parent div, there may be unnecessary nesting.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to eliminate the first even number from a string?

My task involves working with a string containing only numbers. For example: let inputString = "1234"; The Challenge I need to create a function that will return the string excluding the first even number, if one exists. Example Output: " ...

Configuring Webpack for a React application with Express and Babel

I am in the process of developing a React application, utilizing React version ^15.6.1 along with Webpack, Express, Babel, and Yarn as the package manager. After successfully running the application, I am now preparing to transition it to production by co ...

Can you explain which variable is considered global in Node.js?

Instead of writing var global = window for the browser I want my code to be able to work in a node environment as well. Something like var global = window || node_global What is node_global? I couldn't find any clear answer here: or here https ...

My Node.js script seems to be experiencing some issues

Could you provide me with a helpful tip? Here is the code I am working on: const request = require('request'); const cheerio = require('cheerio'); function getUrls(url) { const baseUrl = 'https://unsplash.com'; let u ...

Clone content upon pressing the Enter key

I am facing an issue with my editable container where I have a div inside it. Whenever I press enter, the div duplicates, resulting in two divs stacked on top of each other. The container has contenteditable set to true, which might be causing this problem ...

JavaScript/CSS manipulation: The power of overriding animation-fill-mode

When animating text using CSS keyframes, I use animation-fill-mode: forwards to maintain the final look of the animation. For example: #my-text { opacity: 0; } .show-me { animation-name: show-me; animation-duration: 2s; animation-fill-mod ...

Extracting dynamic content from a webpage using Selenium with Javascript rendering capabilities

Seeking a way to extract data that populates the SVG elements on a specific page: The page seems to be driven by JavaScript, making traditional BeautifulSoup methods in Python ineffective. After inspecting the network for XHR requests, it doesn't see ...

Angular.js: The $setDirty() method on a form does not automatically affect its child form elements

Currently, I am working on a form validation project using Angular.js. A specific challenge that I am facing is setting the dirty state on a child element of a form in an isolated scope within a directive. Does anyone know how to achieve this and set the i ...

Determining the Clicked Button in React When Multiple Buttons are Present

Within my functional component, I have a table with rows that each contain an edit button. However, when I click on one edit button, changes are applied to all of them simultaneously. How can I identify which specific button was clicked and only apply chan ...

Encounter an issue during npm installation of electron: "Error verifying the initial certificate."

I recently developed a new app directory and ran the command npm init. However, I encountered an issue while trying to install Electron with the following line of code: npm install electron --save-dev. The error message I received is as follows: > [em ...

The webpage Page.php is failing to display the newly added content

I have a collection of logos on my homepage (index.php) in WordPress, and they are positioned at the bottom just as I intended. However, these logos do not appear on all pages. Even if I add the exact same code to the page.php file in the exact position, ...

Best practices for declaring variables in ReactJS

I need help understanding how to declare a variable in a React JS class so that it is accessible in different functions. Here is my code snippet: class MyContainer extends Component { constructor(props) { super(props); this.testVariable ...

Discovering the absent number within a cyclical array

Looking to find the missing number between two arrays in a cyclical manner using either Javascript or jQuery. It's easy to find all missing numbers, but I specifically need to identify the single missing number within the range of the second array whi ...

Can you transform a character array into an array of objects in Java? Is this doable?

public static String censorInput(String inputString) { Object[] charArray; int length = (charArray = inputString.toCharArray()).length; //THIS LINE OF CODE IS CAUSING A PROBLEM The purpose of converting it to an object is to be able to cast ...

Is there a way to store the outcome of my node api request in a variable and then transmit it using Express?

Currently, I am leveraging Node to initiate an API call to a movie database. This Node API call is enclosed within an Express route. // Mandatory module requirements var express = require('express'); var router = require('./router.js&ap ...

Tips for eliminating the backslash introduced by JQuery

Switching back from framework 4.5 to 4.0 caused several issues that needed fixing. One significant change I noticed was that jQuery started escaping double quotes. Is there a way to stop this behavior? I attempted datatest = datatest.replace("\\ ...

Error encountered in thread "main": Issue with parsing string literal

import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class FindElementsUsingJS { static WebDriver driver= new FirefoxDriver(); public static void main(Stri ...

What causes the component to remount with every update to its state?

PLEASE NOTE: Before posting this question, I realized that there were some errors in my code. I understand now that this question may not be helpful to others as it contains misleading information. I apologize and appreciate those who took the time to res ...

Error encountered: Unable to assign onClick property to null object

Hey everyone, I'm running into an issue with my JavaScript. It keeps throwing a TypeError: Cannot set properties of null (setting 'onclick') at SignUp.js:4:43 <HTML> <body> <div class="input-box"> <span class="deta ...

What makes the element[class=noquotes] function so effective?

According to the MDN attribute selector in CSS, it has the following syntax: div[attr="actualValue"] For example: <div class="test"></div> div[class="test"] However, I have observed that the quotes around the test are not necessary as show ...