Draw line between two divs with jQuery DOM line

Question

I want to draw a straight line between two divs and found jQuery DOM line, which seems to be a much smaller, simpler approach than jsPlump.

I want to integrate it into my code, but it does not work. Here is my very basic example:

var fromPoint = $('#first');
var toPoint = $('#second');
$.line(fromPoint, toPoint);

As the docs tell me to do. While the console does not show any errors, the line does show itself neither. Wheres my mistake?

CODEPEN DEMO


Show source
| javascript   | dom   | jquery   2017-01-07 13:01 1 Answers

Answers to Draw line between two divs with jQuery DOM line ( 1 )

  1. 2017-01-07 13:01

    Try this working code : demo

    Actually problem is $.line required object with x and y value as parameter and in above question it passes html element in $.line function. So it was not working. So I have corrected it.

    function getOffset( el ) {
        var _x = 0;
        var _y = 0;
        while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
            _x += el.offsetLeft - el.scrollLeft;
            _y += el.offsetTop - el.scrollTop;
            el = el.offsetParent;
        }
        return { top: _y, left: _x };
    }
    
    var fromPoint = getOffset($('#first')[0]);
    var toPoint = getOffset($('#second')[0]);
    
    var from = function () {},
    to = new String('to');
    from.y = fromPoint.top+10;
    from.x = fromPoint.left+10;
    to.y = toPoint.top+10; 
    to.x = toPoint.left+10;
    
    $.line(from, to);
    
    console.log('All scripts runned');
    

Leave a reply to - Draw line between two divs with jQuery DOM line

◀ Go back