arbitrary arrangement of elements within container element

I need assistance with positioning random elements inside a DIV. These elements have varying LEFT and TOP positions within the parent element

<div class="main"></div>
. How can I mathematically calculate and set these positions using JavaScript/jQuery to ensure that no random element goes beyond the boundaries of the parent container?

Here is an example of the HTML structure:

<div class="main"></div>

This is the JavaScript code snippet used to create and position the random elements:

for (var i = 0; i < 5; i++) {
  $('.main').append('<div class="box"></div>');
}
$( '.box' ).each(function( index ) {
  $(this).css({
    left : ((Math.random() * $('.main').width())),
    top : ((Math.random() * $('.main').height()))
  });
});

You can view an example of this implementation here: https://jsfiddle.net/iahmadraza/u5y1zthv/

Thank you for your help!

Answer №1

To achieve the desired outcome, simply eliminate the fixed dimensions of .box elements which are set at 100px height and width:

$(this).css({
  left: Math.random() * ($('.main').width() - $(this).width()),
  top: Math.random() * ($('.main').height() - $(this).height())
});

Check out the updated fiddle here

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

I am having trouble programmatically setting the 'checked' attribute for a newly added checkbox on an asp.net page

I dynamically added checkboxes using jQuery on my ASPX page and attempted to check some checkboxes by default based on conditions. However, I encountered the following error: Uncaught TypeError: undefined is not a function I tried the following methods ...

PHP problem encountered when trying to assign values to a dropdown menu from an array

Specifically, the error message that I am encountering is: *Notice: Array to string conversion in C:\xampp\htdocs\Project1_Tables\index.php on line 38 Notice: Array to string conversion in C:\xampp\htdocs\Project1_Tables ...

Using JQuery to retrieve part of a className results in a null value being returned

I am facing an issue with a piece of code in codesandbox where it returns null when I attempt to retrieve part of the className from a div using JQuery. How can I troubleshoot this and make it work? Check out the Codesandbox Example import React, { Compo ...

Error Encountered with Google Authentication in Localhost:3001 - Warning of 'Blocked Access'

Encountering a Next-auth Google authentication issue on my localhost development setup. Admin side (localhost:3000) and client side (localhost:3001) of e-commerce website are separate instances. Error message "access blocked" when trying Google authentica ...

css issue with opacity transition not functioning properly

My website is designed to display images in a table, but some of them are Stock Photos, so I need to indicate the source. I want the source to appear when the user hovers over the picture. For this purpose, I have assigned the source tag to a class (.PicSo ...

Is it true that Safari restricts AJAX Requests following a form submission?

I've developed a JavaScript-based upload progress meter that utilizes the standard multipart submit method instead of submitting files in an iframe. The process involves sending AJAX requests during submission to retrieve the percentage complete of th ...

Position the site at the center of the screen for perfect alignment

As I work on building a website, I am striving to achieve perfect center alignment both horizontally and vertically on the screen. However, despite my efforts, I have only managed to center it horizontally so far. After thorough research, the solutions I ...

Arrange an array of objects based on boolean values first, followed by numerical values in JavaScript

I am facing a challenge where I have an array of objects that need to be sorted based on two rules, following a specific order: Firstly, objects with the "departeYet" property set to true should come first. Secondly, the objects must then be sorted numeri ...

Incorporate the class directly into the datepicker input element in a React JS component

Adding a class directly to the input element is what I am trying to achieve here.https://i.sstatic.net/qGGwD.png The class MuiInputBase-input needs to be added. This code pertains to a date picker. import { DateTimePicker, MuiPickersUtilsProvider } from & ...

Incorporate an assortment of facial features into BufferGeometry using three.js

If I have a BufferGeometry, I can easily assign its vertices using an array of type Float32Array with the following code snippet: geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) ); However, is there a way to set the f ...

Issues with Jquery DataTables Component not functioning as expected

I'm a beginner in jQuery and I downloaded this but there aren't enough tutorials available. If anyone knows how to do this correctly, please help me out. It's been difficult for me to figure it out because when I search online, I can't ...

Encountering an issue with the autocomplete feature in the jQuery library where it is stating "this.source is not a function."

Here's the code snippet I'm working with: $.ajax({ type: "GET", url: "https://url.com", dataType: "json", success: function (data) { $("#search").autocomplete({ source: data, select: function (even ...

Troubleshooting a jQuery mobile page loading issue

I'm attempting to implement loadPage with jQuery mobile, but the function isn't returning data to the designated page container. My JavaScript code is as follows: $('.numMobi a').live("click", function() { var dataurl = $( ...

Messaging through Express.js via whatsapp-web.js is not working on the server

After successfully confirming the QR code with my phone, the console displays "READY," but I encounter a "404" error when sending a JSON request to the "/sendmessage" endpoint. The same issue arises when accessing the "/getqr" endpoint. Despite referencing ...

Passing data from input to Angular's $scope (filter)

I'm currently working on my first custom filter, and while the basic principle is functioning (it displays all the CDs of an artist from 7 and up), I'm encountering an issue where the filter doesn't update when I change the value. It consist ...

What are some creative ways to customize the background of a MaterialUI modal design?

I am currently facing an issue with my MUI Modal setup. The backdrop is displaying as black even though I have proper styling in place. No matter what I do, the backdrop remains pitch black and does not update. Below is the code snippet along with a scree ...

It appears that when filtering data in Angular from Web Api calls, there is a significant amount of data cleaning required

It appears that the current website utilizes asp.net web forms calling web api, but I am looking to convert it to Angular calling Web api. One thing I have noticed is that I need to clean up the data. How should I approach this? Should I use conditional ...

The functionality of $(selector).css() seems to be malfunctioning

I currently have an html div element stored in a variable var rows = ""; rows += "<div>1111 : Hi there</div>"; Despite multiple attempts, I have failed to add a background color to this div using the following methods: 1. $(rows).css({&apos ...

Unable to retrieve file with jQuery plugin

My main goals are twofold: first, to hide the URL when a mouse hovers over it successfully; and second, to enable file download on click of an <a> tag. The current issue I am facing is that an error appears when I attempt to click on the <a> t ...