Dynamically size and position elements to fit perfectly within the container

I am currently facing a challenge with my absolutely positioned elements that have different position.top and height values generated from the database.

The main goal is to resolve collisions between these elements by shifting them to the right while adjusting their width to fit within the <body> container.

However, I am encountering an issue when applying the 'left' position to the collided elements.

To detect collisions, I am using a tool available at https://sourceforge.net/projects/jquerycollision/.

Here is the desired final layout:

https://i.sstatic.net/47W2D.png

$('div').each(function() {
  var name = $(this).text();
  var hits = $(this).collision('div').not(this); // Find colliding elements
  console.log(name + ' collides with: ' + hits.length + ' others');

  if (hits.length > 0) {
    var widthAll = 100 / (hits.length + 1);

    // Shift colliding elements to the right with equal width
    $(hits).add(this).each(function(i) {
      var name = $(this).text();
      $(this).css({ 'left': widthAll * i + '%', 'width': widthAll + '%' });
    });
  }
});
div {
  position: absolute;
  width: 10em;
  font-size: 0.75em;
  color: white;
}

.blue {
  top: 0;
  height: 80%;
  background-color: blue;
}

.red {
  top: 15%;
  height: 5%;
  background-color: red;
}

.yellow {
  top: 17%;
  height: 10%;
  background-color: yellow;
  color: black;
}

green {
  top: 30%;
  height: 5%;
  background-color: green;
}

.magenta {
  top: 36%;
  height: 3%;
  background-color: magenta;
}

.cyan {
  top: 50%;
  height: 5%;
  background-color: cyan;
  color: black;
}

.brown {
  top: 81%;
  height: 5%;
  background-color: brown;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://rawgit.com/dsbaars/jquery-collision/master/js/jquery-collision.min.js"></script>

<div class='blue'>blue</div>
<div class='red'>red</div>
<div class='yellow'>yellow</div>
<div class='green'>green</div>
<div class='magenta'>magenta</div>
<div class='cyan'>cyan</div>
<div class='brown'>brown</div>

Answer №1

After carefully reviewing your code and making necessary adjustments based on your requirements, here is the updated version:

  1. The initial block of code ensures that the div elements are shifted to the right to prevent overlapping.
  2. In the second block, the width of the divs is evenly distributed based on the size of the body.
  3. Finally, the last block increases the width of the remaining divs to occupy the available space.

"use strict";
var divs = $('div'),
  mx = 0,
  mxs = [0],
  bw = $("body").outerWidth(),
  steps = 1;
// More JavaScript code goes here...
body {
  margin: 0;
}
// CSS styling for different colored div elements
.blue {
  // CSS properties for blue div
}
.red {
  // CSS properties for red div
}
// Styling for other color divs goes here...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/dsbaars/jquery-collision/master/js/jquery-collision.min.js"></script>

<div class='blue'>blue</div>
<div class='red'>red</div>
// Other colored div elements added in similar manner...

This code snippet is currently non-responsive. To make it responsive, you can simply listen to the resize event, update the value of bw, and repeat the second and third code blocks accordingly.

Note: Due to unresolved bugs in jquery-collision.min.js, consider using an alternative solution suggested by Alex G at .

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

Extract the identifier of the class and subsequently pass it to the PHP script

How do I retrieve the id of a dynamically created class within a while loop, where the id corresponds to the user who posted it, and then send this id to PHP? Here's exactly what I'm trying to achieve: HTML: <div class='lol' id=&a ...

Proceed with the next steps only when the .each() function has finished executing

Is there a way to ensure that a function is called only after the completion of .each()? How can we make sure that postPreparation() runs immediately after $('.element').each() finishes in the code snippet below? $('.element').each(fun ...

Guide on updating a single element in a Firebase array

I have an array stored in my firebase database, structured like this: matches:[ {match:{id:1,data:...}}] I am looking for a way to update just one specific item within this array. Let's say I want to locate the match with the ID of 32 and modify its ...

What is the best way to retrieve ember model relation properties within routes and controllers?

Currently using ember 2.7.0, I am facing an issue while setting up my ember app with a currentUser.organization derived from the authenticated token. Although I can successfully resolve the currentUser, I am encountering difficulties in resolving the prope ...

What is the method for obtaining the properties of a type as an array in Typescript?

In the given scenario: class Foo { constructor( private one: string, private two: string, private three: string) { } } Is there a way to create an array containing the type's properties? For example, I need to gene ...

When a div is floated to the left and another div is floated to the right, the

I would like the footer to display an image aligned to the left and some additional text (an inline ul with links) aligned to the right within the footer. Here is the CSS & HTML: footer { clear: both; background: #113551; width: 90%; ma ...

What is the process for creating a personalized user input in JavaScript?

When entering a tracking number, please ensure it follows this specific format: AB-CDEFG-H. The first character (A) must be a digit between 1 and 9 inclusive. The second character (B) should be an uppercase English letter. This is followed by a hyphen (-). ...

Enhance your website with a stylish drop-down menu from inc.com

I am trying to create a drop and hide menu effect similar to the one on Here is my current demo: http://jsfiddle.net/elementhttp/56ThC/ $("#1").mouseover(function(){ //alert("aaaaaaaaaa"); just for testing $(".block2").stop().fadeToggle(700 ...

Using AJAX asynchronously in JavaScript commands synchronization

After researching similar questions on SO without finding a satisfactory answer, I encountered an issue with synchronous AJAX calls in my HTML/JavaScript page. Mozilla has deprecated some functionality related to synchronous requests, making it necessary f ...

How can we export data to excel using react-export-excel while ensuring certain columns are hidden?

Greetings! I believe the title gives you a clear idea of my dilemma. When exporting data, there are no errors - my goal is to hide the Excel column when the checkbox is unchecked or false, and display it when the checkbox is checked or true during export. ...

Storing multiple values of dynamically added elements in a single variable and accessing them within a function

Is it possible to store multiple values into a single variable and then access them in a setTimeout function? $(document).ready(function (){ div ({'div':'#noo','auto':'true','pos':'top',' ...

There seems to be a glitch with jQuery on my Angular.js website

I'm trying to implement Masonry.js on my website, and although I've managed to make it work, the solution feels like a messy workaround and I can't quite figure out why it's functioning (and not functioning well). The primary issues I& ...

Having difficulty modifying the values of my input types on the edit page

After successfully adding user values from the add user page, I encounter an issue when attempting to edit these values such as firstname and lastname on the edit page. Please review the code snippet below for any possible errors. import React from ' ...

Customize data appearance in Django Admin interface

I am working with a model that has a json field. The data stored in this field may not always be pretty-printed, and I am okay with it as long as it is valid. However, when the data is displayed in Django admin, I would like it to be pretty printed for eas ...

The repetitive occurrence of text is a result of an error in the Ajax data parameter. What should be the correct parameter to prevent

I'm still new to working with Ajax. I've managed to extract the correct values from the PHP URL in my Ajax function, but now I'm facing an issue where the data parameter is causing duplicate values to appear. On the actual webpage, here&apo ...

Showcasing pictures on ReactJS

I am currently working on developing an application to showcase images on my React webpage. These images have already been uploaded to a local folder. In order to integrate my React application with a NodeJS server and MongoDB, I connected the two. My goa ...

Obtain information using AJAX calls with jQuery Flot

Having an issue with jQuery Flot that I need help resolving. PHP output (not in JSON format): [[1, 153], [2, 513], [3, 644]] ~~ [[1, 1553], [2, 1903], [3, 2680]] Here is the jQuery call: $.ajax({ url: 'xxx.php', success: function (dat ...

When the condition fails to activate

I am encountering an issue with my code that involves an if statement checking the value of a variable and binding a mousewheel event based on its true or false value. The problem is, the if condition only triggers on load and not when the value changes to ...

bxSlider adds in an empty slide after deleting an image

Whenever I click a link in my navigation, I want to remove certain images from the page. I tried implementing a solution, but now I have two empty spaces where the images used to be. How can I remove those as well? I searched on Stack Overflow for a soluti ...

How can I update an Angular Datatable to display new JSON data?

I have a Datatable controller set up as shown below: //Module / Módulo var angularDataTables = angular.module("angularDataTables", ['datatables', 'datatables.buttons' , 'datatables.bootstrap']); //Controller / Controlador ...