Search code examples
javascriptfunctionmethodssetintervaloverlap

setInterval function for elements overlapping while transitioning,


I want to optimize. Blue/green are checked for overlapping using setInterval and if they do blues sent below green until they no longer intersect. However, many times they are not made to intersect and instead may move further away or closer to each other but not quite reach overlapping. What are ways to check for overlapping when green/blue are going to overlap and not when they're not and any other ways this can be simpler? Also my use of this method doesn't use variables that inversely correlate equally like this example, therefore solutions like (if rand>50%) won't help. Thanks!

var green = document.getElementById('green');
var blue = document.getElementById('blue');
        
function myFunct1() {
    var array = ['10%','20%','30%','40%','50%','60%','70%','80%']  
    var rand = array[Math.floor(Math.random()*array.length)];
    green.style.left = rand;
    blue.style.right = rand;
    var inter = setInterval(overlay, 50);
    setTimeout(function( ) { clearInterval( inter ); }, 1500);
}

function overlay() {
    var greenRect = green.getBoundingClientRect();
    var blueRect = blue.getBoundingClientRect();
    var overlap = !(greenRect.right < blueRect.left || greenRect.left > blueRect.right)
            
    if (overlap == true) {
        blue.style.top = '20px';  
    }
    else {
        blue.style.top = 'auto';
    }
}
#container {
   position: relative;
   width: 90%;
   height: 40px;
   margin: auto;
   border: 1px solid black;
 }

#green {
  position: absolute;
  width: 50px;
  height: 20px;
  left: 10px;
  background-color: green;
  transition: 1500ms;
 }
        
#blue {
  position: absolute;
  width: 50px;
  height:20px;
  right: 10px;
  background-color: blue;
  transition: 1500ms;
}
<div id = 'container'>
    <div id = 'green'></div>
    <div id = 'blue'></div>
</div>
        
<button onclick = 'myFunct1()'>FUNCTION 1</button>


Solution

  • How about adding some overlap tolerance,

    I have only added on one of the two boxes but ofcourse, you can split the overlap and apply them on both boxes

    function overlay() {
        var overlappingTolerance = 10
        var greenRect = green.getBoundingClientRect();
        var blueRect = blue.getBoundingClientRect();
        var overlap = !(
                           ( greenRect.right - overlappingTolerance)  < blueRect.left ||
                           ( greenRect.left - overlappingTolerance) > blueRect.right
                       );
    
        if (overlap == true) {
            blue.style.top = '20px';  
        }
        else {
            blue.style.top = 'auto';
        }
    }