Search code examples
javascriptjqueryjquery-uicss-transitionsuc-browser

Two DIVS keep distance when overlaps each other


I have two DIVS which html code is given

function collision($div1, $div2) {
	var x1 = $div1.offset().left;
	var y1 = $div1.offset().top;
	var h1 = $div1.outerHeight(true);
	var w1 = $div1.outerWidth(true);
	var b1 = y1 + h1;
	var r1 = x1 + w1;
	var x2 = $div2.offset().left;
	var y2 = $div2.offset().top;
	var h2 = $div2.outerHeight(true);
	var w2 = $div2.outerWidth(true);
	var b2 = y2 + h2;
	var r2 = x2 + w2;

	if (b1 < y2 || y1 > b2 || r1 < x2 || x1 > r2) return false;
	return true;
}

window.setInterval(function () {
	$('#result').text(collision($('#div1'), $('#div2')));
	if (collision($('#div1'), $('#div2')) == true) {
		$('#div1').addClass('touch');
		$('#div2').addClass('touch');
		$('#div1,#div2').css();
	}
	if (collision($('#div1'), $('#div2')) == false) {
		$('#div2').addClass("remTouch");
		$('#div1').addClass('remTouch');
	}
}, 200);

$('#div1').draggable();
.touch{
    margin:20px;
    transition: margin 1s;
}
.remTouch{
    margin:-20x;
    transition: margin 1s;
}
#div1 { 
    width: 100px; height: 100px; background-color: pink;
    border-radius: 50%;
    opacity: 0.7;
}
#div2 { 
    width: 200px; height: 200px; background-color: green; 
    border-radius: 50%;
    opacity: 0.7;
}
<link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />

<div id="div1"></div>
<br/>
<div id="div2"></div>
    
<p>Colliding? <span id="result">false</span>
    
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

Now the problem is that when i move the small div towards the bigger one, after overlapping it moves but while during false condition nothing happens, I mean when condition is false i want to move the bigger div back to its position. More specifically i want the bigger div to run away smoothly from the smaller div and keep a little distance. I want to do it just like UC browser has done it. Thank you so much in advance.


Solution

  • I have updated the fiddle. https://jsfiddle.net/uv4uurzn/3/ JS change:

      var newTop =  $('#div1').offset().top + 150;
      var newLeft =  $('#div1').offset().left + 10;
      console.log(newTop);
      $('#div2').css('top', newTop);
      $('#div2').css('left', newLeft);
    

    CSS update:#div2 { width: 200px; height: 200px; background-color: green; position: fixed; top: 150px; left: 10px; border-radius: 50%; opacity: 0.7; -moz-transition: all 250ms ease-out; -webkit-transition: all 250ms ease-out; }

    you can set div to fixed position and set top left as per your desire.