In my code, I used Jquery UI to make the elements draggable for easy debugging. The code I wrote with the help of someone tells me if the rounded divs are overlapping each other but I want to check if a rounded div is overlapping a square div. How can I do that?
BTW If you remove the round class the div will become a square.
let $label = $('.overlap-label span');
const hasOverlap = (x0, y0, r0, x1, y1, r1) => {
return Math.hypot(x0 - x1, y0 - y1) <= r0 + r1;
}
const coordinates = (className) => {
const val = document.querySelector(className);
const rect = val.getBoundingClientRect();
return {
y: rect.top + val.offsetHeight / 2,
x: rect.left + val.offsetHeight / 2,
rad: val.offsetHeight / 2
}
}
const checkForOverlap = () => {
const cm = coordinates(".circle.small");
const cl = coordinates(".circle.large");
$label.text(hasOverlap(cm.x, cm.y, cm.rad, cl.x, cl.y, document.querySelector(".circle.large").offsetHeight / 2));
}
$('.parent').draggable().on('drag', checkForOverlap);
.circle {
width: var(--square);
height: var(--square);
background: var(--bg);
display: inline-block;
}
.round {
border-radius: 50%;
}
.parent {
display: inline-block;
}
.small {
--square: 50px;
--bg: red;
}
.large {
--square: 100px;
--bg: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/themes/base/jquery-ui.min.css" />
<div class="overlap-label">Circles are overlapping? <span>false</span></div>
<div class="parent">
<div class="circle small round"></div>
</div>
<div class="parent">
<div class="circle large round"></div>
</div>