JSFiddle - React, Tailwind, and code Playground
by John Doe
HTML
<div id="one" class="point"></div>
<div id="two" class="point"></div>
<div id="three" class="point"></div>
<div id="four" class="point"></div>
<svg id="svg">
<line id="line" class="line original" stroke-dasharray="5, 5"/>
</svg
SCSS
html, body{
margin: 0;
padding: 0;
}
#svg{
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100vh;
}
#line{
stroke-width:2px;
stroke:rgb(0,0,0);
}
//styling
.point{
width: 150px;
height: 15px;
background: #d54501;
position: absolute;
z-index: 10;
}
body {
font-family: 'Niramit', sans-serif;
background-color: #b2ada3;
}
p {
margin-left: 20px;
margin-right:20px;
position: relative;
z-index: 11;
background: rgba(178, 173, 163, .55)
}
#one{
top: 80px;
left: 50px;
}
#two{
top: 290px;
right: 50px;
}
#three {
top: 390px;
right: 150px;
}
#four {
top: 590px;
left: 20px;
}
.btn {
display: inline-block;
background: #4e7c80;
color: white;
padding: 10px 15px;
margin-left: 5px;
cursor: pointer;
position: relative;
z-index: 11;
line-height: 1em;
&:hover {
background: darken(#4e7c80, 10%);
}
}
JavaScript
const config = {
target: $(".point"),
line: $(".line"),
delay: 40 // enter zero for live resizing
}
const drawBetweenObjects = {
//cmake the line
makeLine: function(line, div1, div2) {
var className = div1.attr('id') + div2.attr('id');
if ( className.includes("undefined") !== true ) { //error check
$(line).clone().addClass('deleteMe').addClass(className).removeClass("original").insertAfter(line);
//calculations (for legibility, these are separte vars)
var x1 = div1.offset().left + (div1.width()/2);
var y1 = div1.offset().top + (div1.height()/2);
var x2 = div2.offset().left + (div2.width()/2);
var y2 = div2.offset().top + (div2.height()/2);
$("."+className).attr('x1',x1).attr('y1',y1).attr('x2',x2).attr('y2',y2); //svg attributes
} else { console.error("undefined object") }
},
findLines: function(search) {
$(".deleteMe").remove(); //remove last set of lines
$(search).each(function(index, el){
if ( search.eq(index + 1).length ) { //only do drawBetweenObject if there is another.
drawBetweenObjects.makeLine(config.line, $(this), search.eq(index + 1)); //args order - line, div1 and div2 - the next div.
}
});
},
init: function() {
drawBetweenObjects.findLines( config.target );
//give resizing time to happen
var resizeId;
$(window).resize(function() {
clearTimeout(resizeId);
if (config.delay !== 0) {
resizeId = setTimeout(doneResizing, config.delay);
} else {
drawBetweenObjects.findLines( config.target );
}
});
function doneResizing(){
drawBetweenObjects.findLines( config.target );
}
}
}
drawBetweenObjects.init();