Draw a connecting line between two elements
To draw a line between two elements, mainly two approaches exist: the first relies on CSS's ::after
for static positioning, the second entails SVG and JavaScript for dynamic scenarios.
CSS-only solution using the ::after
pseudo-element:
Corresponding HTML:
SVG & JavaScript to draw lines in real-time:
Implement with SVG:
Invoke with:
Advanced usage: Libraries for interactive draggable connections
Some situations require more than just a static line between two elements. Let's examine some libraries and techniques to draw interactive, draggable and editable connections.
jsPlumb: Interactive line drawing
Using jsPlumb, you can create draggable and editable connections between elements. It comes in two flavors, the Community edition which is free and the Toolkit edition (commercially licensed) for fancier use cases.
SVG & jQuery: Dynamically updating lines
With a blend of SVG and jQuery, you can create lines that dynamically adjust based on the current position of the elements. You can use jQuery's position()
and .attr()
methods to update the endpoints of an SVG line.
VisJS & Leader Line: Data-rich applications
For applications handling data-rich elements, libraries such as VisJS and Leader Line provide excellent support for draggable elements and editable connections.
Advanced scenarios – The extra mile
Drawing curves with Bezier.js
Want to add some style to your connections? Bezier curves can make the lines between your elements follow elegant, curved paths.
Data-driven applications with jQuery
Knowing when your data changes and being able to reflect it in your UI is critical in many applications. Using jQuery's .data()
and .attr()
methods can help you accomplish this more effectively.
Accessible SVGs
Making your SVG accessible isn't just about complying with WCAG guidelines (which you should), it's also about creating a better experience for all users.
Was this article helpful?