Creating line between two HTML elements using jQuery

Posted By : Deepak Rawat | 31-Mar-2015

CSS Hacks For All Browsers

Hi guys,

Ever wondered how to create line between two html elements without using canvas. Here I’ll tell how to create one, by using the below code you can create line between two HTML elements no matter where they are in the document, this function uses some mathematics functions like Math.sqrt() &  Math.atan2(), and dynamically find the position of the two elements and draw the line between them, by this code you don’t have to worry about rotating the line because this code also calculates the angle between those two elements and rotate the line automatically.

 

Math.atan2() : is an arctangent used to calculate the angle which rotates the line.

Math.sqrt() : is use to calculate the distance between those elements


Here is a code which you can use to create the line :

 

function createLine(el1, el2){
	var off1 =getElementProperty(el1);
    var off2 =getElementProperty(el2);
    // center of first point
    var dx1 = off1.left + off1.width/2;
    var dy1 = off1.top + off1.height/2;
    // center of second point 
    var dx2 = off2.left + off2.width/2;
    var dy2 = off2.top + off1.height/2;
    // distance
    var length = Math.sqrt(((dx2-dx1) * (dx2-dx1)) + ((dy2-dy1) * (dy2-dy1)));
    // center
    var cx = ((dx1 + dx2) / 2) - (length / 2);
    var cy = ((dy1 + dy2) / 2) - (2	 / 2);
    // angle
    var angle = Math.atan2((dy1-dy2),(dx1-dx2))*(180/Math.PI);
    // draw line

    return  "<section class='connectingLines' style='left:" + cx + "px; top:" + cy + "px; width:" + length + "px; -webkit-transform:rotate(" + angle + "deg); transform:rotate(" + angle + "deg);'></section>";
  };

function getElementProperty(el){
	var dx = 0;
	var dy = 0;
	var width = el.width()|0;
    var height = el.height()|0;
    
    dx += el.position().left;
    dy += el.position().top;
    
    return { top: dy, left: dx, width: width, height: height };
};

 

The createLine() function returns the HTML of the line created and you just have to append the code inside the element where the two element persist.

The getElementProperty() function provides the position of each of the elements, it returns the properties like position from top & left and it provides height & width of the elements also.

When you done, here what you can do with this:

Have fun..!!

THANKS

 

About Author

Author Image
Deepak Rawat

Deepak is a Web and Mobile application Sr. Lead Frontend developer and good working experience with JQuery , AngularJS , Javascript and PhoneGap. His hobbies are listening to music and photography.

Request for Proposal

Name is required

Comment is required

Sending message..