0

I would like to draw a line that can be styled, that starts from the center position of a <td> element, and ends at the center position of another <td> element.


I've already tried using jQuery Connections plugin, but it connects the edges of the elements, not the center position.

This plugin would simply work like this:

$('#start').connections({
  to: '#end',
  'class': 'related'
});

I want it to work the same way. (or a similar way)


Also when I do use the jQuery Connections plugin, the connector line apparently does not appear.

1
  • 1
    Its very easy to do this with svg, if you could write your own, so do try and then post what you tried and also a mini demo so we could look at what you have tried and also see the problem
    – Alen.Toma
    Commented Jun 23, 2019 at 10:07

2 Answers 2

6

After a long while, I've finally found a solution. Use getBoundingClientRect() on the two elements, then create a SVG line element. The SVG is fixed at the top-left corner of the window, and it's possible to click through using pointer-events: none;.

var b1 = document.getElementById('btn1').getBoundingClientRect();
var b2 = document.getElementById('btn2').getBoundingClientRect();
var newLine = document.createElementNS('http://www.w3.org/2000/svg', 'line');
newLine.setAttribute('id', 'line1');
newLine.setAttribute('x1', b1.left + b1.width / 2);
newLine.setAttribute('y1', b1.top + b1.height / 2);
newLine.setAttribute('x2', b2.left + b2.width / 2);
newLine.setAttribute('y2', b2.top + b2.height / 2);
newLine.setAttribute('style', 'stroke: black; stroke-width: 2;');
document.getElementById("fullsvg").append(newLine);
#btn1 {
  margin-left: 50px;
  margin-bottom: 5px;
}

#btn2 {
  margin-left: 150px;
}

#fullsvg {
  left: 0px;
  top: 0px;
  position: fixed;
  margin: 0;
  pointer-events: none;
}
<input type="button" id="btn1" class="btn" value="button1"><br>
<input type="button" id="btn2" class="btn" value="button2">
<svg id="fullsvg"></svg>

2

A solution will be to use and extra item inside your td and use display flex and align center, something like this:

<div>
  1
  <span class="line"></span>
</div>

and then:

div {
 display: flex;
 align-items: center;
 width: 100%;
}
.line {
  border-bottom: 1px solid #000;
  width: 100%;
  display: inline-block;
}

Working example here, however you need to adapt it for your needs, but it should do the job: https://codepen.io/anon/pen/ewWgpV

1
  • Great job, it works, but I don't just want it horizontally. I want the line to start and end in the center of two elements, and in the center position of the element, not the closest edge.
    – mekb
    Commented Jun 23, 2019 at 10:37

Not the answer you're looking for? Browse other questions tagged or ask your own question.