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>