What steps can I take to avoid random divs from overlapping on smaller screens when dealing with elements created in the created() hook?

I encountered an issue with the code I'm working on (the circles overlap in the fiddle provided, but display correctly on my PC - possibly due to pixel discrepancies in the fiddle). You can find the code here.

TestCircle.vue:

<template>
  <div class="circle" :style="{left: this.left,
                 top: this.top}">
    {{value}}
  </div>
</template>
...

When I visit TestPage, this is what I see:

https://i.sstatic.net/ky96b.png

Upon refreshing the page:

https://i.sstatic.net/VrC3s.png

https://i.sstatic.net/G3icC.png

...

EDIT:

To be direct, my question is: How can I make the code responsive on mobile devices?

Answer №1

  1. When working with the DOM, it's important to use the mounted hook instead of the created hook. This is because in the mounted hook, the component has been added to the DOM, and you will need the available width for the next step.

  2. Before translating your idea into code, make sure to logically define each step. To achieve the desired functionality, consider creating a function that calculates the minimum height of a box with a given width that can fit all the circles, regardless of their position. Trigonometry may be required to solve this. If you're stuck, you can seek help on a platform like mathematics.

  3. Once you have the formula for the minimal height, your current approach should work, provided you correct the overlaps function to accurately check for circle intersection based on the sum of their radiuses.


If you prefer a rough estimation without seeking help on a mathematics website, consider a pattern where circles are spaced out to avoid overlapping. The distance between centers is approximately 3.5 × r, and each subsequent row has a height of around 3 × r.

If solving this problem, I would estimate the minimum box height based on this pattern, simplifying the formula for the first row's height to ensure the circles fit even if positioned in a seemingly random pattern.


For a rough calculation of the minimum height, you can consider the following formula:

const height = Math.max(
  (3 * radius) * (circles.length / (containerWidth / (3.5 * radius))),
  radius * 3.5
)

Alternatively, you can simplify it to:

const height = Math.max(
  10.5 * circles.length * radius ** 2 / containerWidth,
  3.5 * radius
)

To prevent endless looping, you can set a counter on the while loop. If it exceeds a certain value, consider recalculating the circles. However, the likelihood of freezing is minimal. The counter mechanism is not included in the provided code example.

Try the demo below utilizing this formula:

// Code demo here
// CSS demo styles here
// HTML structure for the demo

If you prefer using the Options API:

// Code snippet for Options API
// CSS style for Options API snippet
// HTML structure for Options API example

Note that on the resize event, positions of circles outside the current container are recalculated to keep them within the visible area.

Answer №2

Since you are interested in placing the circles randomly within a specific area, traditional CSS layout techniques won't be helpful. You'll need to create a mathematical algorithm to calculate the coordinates manually.

To solve this problem, you'll need to determine the coordinates of multiple circles within a defined space without overlapping:

getCoordinates(numberOfCircles, circleSize, areaWidth, areaHeight)

If you already have the algorithm (even if it's somewhat basic), the next step is to dynamically adjust the areaWidth and areaHeight (rather than hardcoding them) and monitor when they change so you can update your algorithm.

To achieve this, you can use Vue's template ref to access the container div (Note that template refs are not available until the mounted hook), and then utilize ResizeObserver to observe any size changes in that div. Whenever the size changes, simply run your getCoordinates function again to update the coordinates, with Vue handling the rest of the process.

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

JavaScript regular expression for detecting valid currency values

I am encountering an issue with removing decimal values from a monetary amount retrieved from a JSON feed: For example, if I have: 150,000, I want to display it as just 150 Here is the code snippet I am using: $.getJSON('/static/js/datatest.json&ap ...

Issue encountered while using AJAX to load images

Currently, I am utilizing a jQuery plugin to fetch images from Flickr. My aim is to organize these images into 3 columns dynamically as they are loaded, ensuring that each image is placed in the shortest column to achieve close to equal lengths for all col ...

The Google Geo Charts fail to load when initiated by Ajax requests

My goal is to use ajax to load an external HTML page that includes the following code: <script type='text/javascript' src='https://www.google.com/jsapi'></script> <script type='text/javascript'> function ...

Bar chart with overlays in Chart.js

I am currently working with a ChartJS bar chart and attempting to create overlapping bars. Each date should have three bars, each overlapping the others. Here is my idea: The bar with the highest value should have a z-index of 0, making it the tallest co ...

Is the navigation component's loss of properties due to a React router error?

After implementing react router for the first time, I noticed that the props passed to my nav component get lost once a new route is rendered. It's like the items in the cart are disappearing when I click checkout, but reappear correctly when I go bac ...

Using TypeScript with React Bootstrap's <Col> component and setting the align attribute to 'center' can trigger a TS2322 warning

The React app I'm working on includes the code below. The Col component is imported from React-bootstrap <Col md={5} align="center"> This is a column </Col> When using Typescript, I received the following warning: ...

Place the Div in a consistent position on images of varying widths

I have a dilemma with my class that is supposed to display images. The issue arises when I try to place a div within an image inside this class. Everything works smoothly when the image takes up the entire width of the class, but as soon as the image widt ...

Utilizing the CSS :not() selector within a nested table

I am having an issue with my AjaxControlToolkit where the main-page CSS is affecting the inner "calendar" popup. To illustrate what I need, what I've tried, and the temporary workaround, I have simplified everything into a one-page example. I am in s ...

jQuery parallax effect enhances scrolling experience with background images

My website features a parallax design, with beautiful high-resolution images in the background that dominate the page. Upon loading the site, the landing page showcases a striking, large background image alongside a small navigation table ('about&apos ...

Toggle the class to slide in or out of the div

I am attempting to create a header with two positions - one absolute and one fixed. I want the header to smoothly slide in as you scroll down, and then slide out when you scroll back to the top. However, I am having trouble getting it to slide; instead, it ...

When an HTML page is hosted on an external server, its formatting may

I recently put together an HTML page that incorporates some CSS and two simple highcharts from highcharts.com. After testing the page on my local machine and being satisfied with the outcome, I transferred it to a server on our internal network to make it ...

Challenges with z-index in Chrome/Safari and Firefox when nesting elements

In the current setup, it seems that .second needs to be positioned above .third, which is only happening in Firefox. Unfortunately, I am facing difficulty as I cannot separate .second from .fifth. Just to provide some context: .third is intended to act as ...

Creating a Set of Buttons in HTML

Need some assistance with grouped buttons. Let's consider a scenario where there are 5 buttons on an HTML page. When the 3rd button is clicked, buttons from 0 to 3 should change color and the function should return 3. Similarly, when the 5th button is ...

Utilize MaterialUI's Shadows Type by importing it into your project

In our project, we're using Typescript which is quite particular about the use of any. There's a line of code that goes like this: const shadowArray: any = Array(25).fill('none') which I think was taken from StackOverflow. Everything s ...

determining the file size of images being loaded remotely by retrieving their image URLs

There is a straightforward regex function in jQuery that I'm using to automatically add an image tag to image URLs shared by users. This means that when a user posts something like www.example.com/image.jpg, the image tag will be included so that user ...

Encountering a CORS header issue while working with the Authorization header

Here is the code snippet I am currently working with: https://i.stack.imgur.com/DYnny.png Removing the Authorization header from the headers results in a successful request and response. However, including the Authorization header leads to an error. http ...

Remove Bootstrap-Table's box-shadow on the search bar's delete button

Is there a way to eliminate the box-shadow from the search box upon clicking on it? I am familiar with removing box-shadows from classes in CSS, but I am unsure of how to remove the box-shadow from a specific property like "data-search" within the tag. ...

Choose the element excluding a particular child

My issue is: I have a div with multiple children and I am trying to figure out how to exclude a specific element that is a child of the previously selected element. I attempted using the :not(selectedElement) selector as well as the .not(selectedElement) ...

Form submission requires a checkbox to be checked

I have been searching for a way to make checkboxes required. Is there a method similar to using required="required"? Currently, I generate my checkboxes in the following manner and would really appreciate any guidance on this topic. It's crucial for m ...

Obtaining documents through Mojolicious

Just a quick inquiry - I have successfully generated a .doc file using my mojolicious app with the help of the CPAN module MsOffice::Word::HTML::Writer. Now, the challenge I'm facing is figuring out how to make the browser initiate the download proces ...