0

I've recently followed this example but I'm struggling to get the live position of div's and updating the connecting line with the relevant position.

Lines connecting to responsive elements

Example of my work here https://jsfiddle.net/spencer1997/vktg31e2/24/

How to draw a line between two divs

Need it to be something like this :

$('.btn').animate({ 'margin-left':'200px', 'margin-top':'70px'}, 3000)

setInterval(function(){
 var div = $('.btn').offset();
 $( ".live-position" ).text( "left: " + div.left + ", top: " + div.top );
}, 100);

https://jsfiddle.net/rpgpp2mp/

Any help will be greatly appreciated.

m4n0
  • 29,823
  • 27
  • 76
  • 89

1 Answers1

0

this shall do the trick, it relies on maths essentially, if you want to change teh position either of the line or the text, you have to change the top and left value so that the angle is still valid and add an offset top and left

$('.btn').animate({ 'margin-left':'200px', 'margin-top':'70px'}, 3000)

const int = setInterval(function(){
 const btn = $('.btn').offset();
 $( ".live-position" ).text( "left: " + btn.left + ", top: " + btn.top );
 const line = document.getElementById("line")
 const angle = Math.atan(btn.top / btn.left);
 line.style.transform = `rotateZ(${angle}rad)`;
 line.style.width=`${Math.sqrt(Math.pow(btn.top, 2)+Math.pow(btn.left, 2))}px`
 
}, 100);

setTimeout(() => clearInterval(int), 3000)
#line {
  display: block;
  background-color: red;
  height: 2px;
  width: 5em;
  transform-origin: top left;
  position: absolute;
  top: 0;
  left: 0;
  
}

.btn {
  top: 0;
  left: 0;
  position: absolute;
}
<div>position: <p class="live-position"></p></div>
<div class="btn">text</div>
<span id="line"></span>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
midugh
  • 608
  • 5
  • 21
  • Awesome, I'll try to implement that into my work, a rough example of it is below. https://jsfiddle.net/spencer1997/vktg31e2/24/ – Spencer1997 May 06 '21 at 18:10