Tips for creating a connecting line between two elements

I am currently working on developing a tree-like structure. I have successfully created numbers within circles using HTML badges. However, I am facing difficulty in drawing lines connecting one element to another. I attempted using left and right diagonal images but that did not work as expected.

Below is the HTML code snippet for creating Badges:

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;<span id="0" class="cl w3-badge">0</span><br><br><br><br>
<span id="1" class="cl w3-badge">0</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<span id="2" class="cl w3-badge">0</span> 

Here is my JavaScript snippet:

var data = [];
data.push(5);
data.push(6);
data.push(4);
$('.w3-badge').each(function(i, obj) {
 document.getElementById(i).innerHTML = data[i];
});

You can find the image of the left line here

If anyone has any suggestions or solutions, please reach out to me. My goal is to achieve a final tree structure similar to this: Final Tree Image

Answer №1

When it comes to creating interactive visuals on a web page, using SVG is the way to go. I have crafted a handy function below that will help you achieve your desired outcome. Remember, you may need to tailor it to suit your specific requirements.
Make sure to view the entire page to see the results in action.

function connectDivs(div1, div2){
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
 svgPath = document.createElementNS("http://www.w3.org/2000/svg", "path");
var div1Offset = div1[0].getBoundingClientRect();
var div2Offset = div2[0].getBoundingClientRect();
            var pathData = "";
            pathData = "M"+ (div1Offset.width + div1Offset.left)+ " " +  ((div1Offset.top + div1Offset.height) / 2)
            pathData += "h" +( div2Offset.left)
            pathData += "v" +(div2Offset.top)
            pathData += "h" +( -div2Offset.left )
            svgPath.setAttribute("d", pathData);
            svgPath.setAttribute("stroke", "red");
            svgPath.setAttribute("stroke-width", "1");
            svgPath.setAttribute("fill", "white");
            svgPath.setAttribute("id", "test");
            svg.appendChild(svgPath);
            $("body").append(svg);

}

$(document).ready(function(){

connectDivs($(".box_1"), $(".box_2"))

});
.box{
width:150px;
height:150px;
margin:30px;
background:black;

}

svg{
position:absolute;
left:0; top:0;
width:100%;
height:100%;

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='box box_1'></div>


<div class='box box_2'></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to alter the background behind each word in a text using only CSS?

I have a question about styling quotes by highlighting each word in the text with a background color. The issue I'm facing is that when using a solid background, there are no gaps between the colors. How can I achieve a result similar to this, but wit ...

Create numerical arrays using specific algorithms

I am in need of several arrays: array 1 = [1,9,17,25,33,41]; array 2 = [2,10,18,26,34,42]; and so on. Each array should increment by 8 from the previous one. I want to create this dynamically using JavaScript functions. ...

"Troubleshooting AmCharts: How to Resolve Missing Data on Graphs/Implementing AJAX for AmCharts Data Visualization/Querying a Database to Dynamically

After writing some HTML and JavaScript code, I'm trying to set up an amcharts plot. To do this, I fetch data from a database using PHP, convert it into JSON format, and then pass it to the graph for display. The issue arises when I try to assign the ...

Create a page that expands to full height with the ability to scroll

I am trying to achieve a layout using flex that fills the entire height of the screen. https://i.sstatic.net/s1RA5.png My goal is to have a red background that scrolls based on the content inside. If there is more content, I want it to maintain the same ...

Ways to avoid Bootstrap popovers from automatically breaking lines

I am struggling with adding a tooltip using Bootstrap's popover. Here is what I have tried: <ul> <li>Entry 1 ....................................................................</li> <li>Entry 2 ...................... ...

Encountering an error of "Object Expected" when trying to implement the

I am trying to set up the suckerfish menu as demonstrated on this instructional website. I keep getting an "object expected" error from the sample JavaScript code: $(document).ready(function () { $("#nav-one li").hover( function () ...

Choose an option from the dropdown menu using a variable

I've been struggling to get a dropdown's selected value to change based on a query result. No matter what I do, it always defaults to the first option. After searching through numerous similar questions, none of the solutions seem to work for me ...

Utilizing AJAX requests in PHP's MVC framework

I am currently working on a game site using a combination of php and javascript. All my classes and data are stored in php and then encoded into json format. The view calls a javascript file which, through an ajax request, retrieves the php data encoded in ...

Refresh the pagination in a jQuery DataTable

I have incorporated DataTable for pagination within my table. The data in the table is loaded through ajax requests, and I am utilizing my custom functions to populate the table manually by interacting with its DOM elements. However, I am facing an issue ...

IE11 is unable to display the background image

I am attempting to create a process roadmap by using background images on list items. The background-image on the list item is not showing up in IE11 (also in all versions of IE10, 9, etc). CSS CODE body{padding: 50px 0;} .status-line { width: 80%; ...

Creating a Framework for CSS Project-Wide Variables

Having experience in mobile development, I am accustomed to using a shared stylesheet that sets the basic styles for the entire project. In Flutter, this would be translated into CSS as follows: :root { // Setting spacing values sizeSm: 8px; // or ...

Is there a way to calculate the total of input fields with similar names?

My goal is to accomplish the following: <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script> $(document).ready( ...

Leveraging AJAX Response for Ending a Parallel Query

Imagine initiating an AJAX HTTP Request through jQuery to a PHP script on the back-end that interacts with a MySQL server. What if, during this request, you want to create a new one and halt the existing process on the server? The file front-end.php has t ...

Clearing inputs upon page loading

After loading the page, I'm encountering an issue where specific inputs are getting cleared. Initially, on document ready, jQuery is populating certain inputs successfully. However, once the page fully loads, some inputs are mysteriously emptied out. ...

What is the best place in Rails to add @media CSS tags?

Currently, my layout.html.erb contains some CSS rules with @media queries. <style> @media (max-width: 900px) { .green-button{ display: none!important; } .chat_button{ margin-top: 20px!important; } #myCarousel{ ...

Despite the presence of data, MongoDB is not returning any values

I am currently working on a code that utilizes $geoNear to find the closest transit stop to a given GPS coordinate. The issue I am facing is that the result sometimes returns undefined, even though I have confirmed that the data exists in the STOPS collect ...

What is the best way to resize SVG graphics effectively?

I am in need of creating a seating chart. I have generated an SVG with the seats. <div class="seats-map"> <svg xmlns="https://www.w3.org/2000/svg" id="seats-map-svg" viewBox="0 0 1000 300"> <g data-row ...

Tips for preventing Bootstrap 4 from automatically adjusting the height of all columns equally

I am receiving text from a loop that I am formatting into lists inside columns. I am attempting to float all my columns one behind the other without any space, but Bootstrap is applying the same height to all of them. Here is an example of what it currentl ...

Is there a selection of quality PHP-based HTML filters on the market?

Currently working on a project with a PHP frontend, our team is highly concerned about security due to the large number of users we anticipate having. With the potential threat from hackers, it's imperative that we address vulnerabilities related to X ...

Adding classes to a randomly generated <li> element in a unique and one-time fashion

My task involves using jQuery to dynamically add <li> elements inside a <div>: countItems = 60; for (i = 1; i <= countItems; i++) { $('#head #lol').append("<li id='item_"+ i++ +"' clas ...