Creating a box that is connected by lines using JSON data requires several steps. You

I am attempting to dynamically draw a line using the provided JSON data.

I have heard that this can be easily achieved with flexbox.

Important: I would greatly appreciate a solution involving flexbox

This is what I hope to achieve:

https://i.stack.imgur.com/7IH2d.png

Here is the JSON data I have:

var path = [
  [{name:"S",color:"blue",parent:true}]
  [{name:"A",color:"blue"},{name:"B",color:"blue"},{name:"C",color:"blue"}],
  [{name:"D",color:"blue"},{name:"E",color:"blue"}],
  [{name:"E",color:"blue"},{name:"F",color:"blue"}]
]

I have attempted something like this:

.container{
  display:flex;
  max-width:1200px;
  margin-top:100px;
  justify-content:center;
  margin-left: 214px;
}
.container .items{
  padding: 40px 70px;
  border:1px solid rgba(15,30,200,.6);
  margin-right: 90px; 
}

.line{
  flex:1;
  position:relative;
  left:40px;
  width:100px;
  border-top:1px solid red;
  display:inline-block;
}

.line {
    flex: 1;
    position: relative;
    left: 161px;
    width: 91px;
    border-top: 1px solid rgba(15,30,200,.6);
    display: inline-block;
}
<div class="container">
  
  <div class="items"><span class="line"></span>A</div>
  <div class="items"><span class="line"></span>B</div>
  <div class="items"><span class="line"></span>C</div>
  <div class="items">D</div>
</div>

Please assist me with this task. Thank you in advance for your help!

Answer №1

One effective method to achieve this is by utilizing CSS and JavaScript. Your HTML requires a container element, along with the necessary data object, while the CSS and JavaScript functions will take care of the rest.

I have expanded on your provided sample data by adding another "root" to demonstrate the outcome:

function drawPath(selector, path) {
    function draw(directions) {
        return $("<div>").addClass(directions).append($("<div>"),$("<div>"),$("<div>"),$("<div>"));
    }

    let lineNo = -1;
    let lines = [];
    for (let row of path) {
        line = [];
        lineNo++;
        for (let obj of row) {
            if (obj.parent) lineNo = 0;
            line.push(draw("east west"), $("<div>").addClass("box").text(obj.name));
        }
        if (!lineNo) {
            lines.push(line.slice(1));
        } else if (lineNo == 1) {
            lines[lines.length-1] = lines[lines.length-1].concat(line);
        } else {
            lines[lines.length-1][1].addClass("south");
            lines.push([$("<div>"), draw("north west")].concat(line.slice(1)));
        }
    }
    let length = lines.reduce((len, line) => Math.max(len, line.length), 0);
    let pct = (100/length-0.01).toFixed(2);
    // pad lines to the longest length
    lines = lines.map(line => Array.from({length}, (_, i) => line[i] || $("<div>")));
    // flatten
    let $elems = $([].concat(...lines).map(jq => jq.css({flexBasis: pct + "%"}).get(0)));
    $(selector).append($elems);
}

// Demo
var path = [
    [{name:"S",color:"blue",parent:true}],
    [{name:"A",color:"blue"},{name:"B",color:"blue"},{name:"C",color:"blue"}],
    [{name:"D",color:"blue"},{name:"E",color:"blue"}],
    [{name:"E",color:"blue"},{name:"F",color:"blue"}],
    [{name:"S",color:"blue",parent:true}],
    [{name:"A",color:"blue"},{name:"B",color:"blue"},{name:"C",color:"blue"},{name:"D",color:"blue"},{name:"E",color:"blue"}],
    [{name:"E",color:"blue"},{name:"F",color:"blue"}]
];

drawPath(".container", path);
.container {
    display: flex;
    flex-flow: row;
    flex-wrap: wrap;
    color: rgba(15,30,200,.6);
}
.container>* {
    flex: 0 0;
    box-sizing: border-box;
    display: flex;
    flex-flow: row;
    flex-wrap: wrap;
    height: 50px;
}
.box {
    border: 1px solid;
    height: 30px;
    margin-top: 10px;
    margin-bottom: 10px;
    justify-content: center;
    flex-direction: column;
    text-align: center;
}
.container>div>div {
    flex: 0 0 50%;
    height: 50%;
    box-sizing: border-box;
}
.north>div:first-child {
    border-right: 1px solid;
}
.south>div:nth-child(3) {
    border-right: 1px solid;
}
.east>div:first-child {
    border-bottom: 1px solid;
}
.west>div:nth-child(2) {
    border-bottom: 1px solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container"></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

Trouble with buttons in table cells

There is a problem with a button placed in a table cell that spans two rows and does not fill the second row. How can I ensure that this button fills both rows? I have attempted to adjust the height in the button's style as well as in the table cell i ...

Items in a pair of distinct columns

I want to enhance a picture by adding three paragraphs on the left-hand side. Below is my HTML code: <md-toolbar layout-align="center center"> <h3>Traffic Light Component</h3> </md-toolbar> <md-grid-list md-cols ...

Choose a Range of DOM Elements

My challenge is to select a range of DOM elements, starting from element until element. This can be done in jQuery like this: (Source) $('#id').nextUntil('#id2').andSelf().add('#id2') I want to achieve the same using JavaScr ...

Exploring Font Choices: Customizing Your Text Style

I've been attempting to incorporate my own font into my website, but despite researching several Stack Overflow articles, I'm facing various browser-specific and path-related issues. Sadly, I haven't been able to successfully display my font ...

Contrast the table column to a JSON object and modify a different column in an HTML file

This Dashboard is my first venture into using HTML and Javascript to create an interactive display. The table within this Dashboard showcases server names, descriptions, and time-related columns for uptime, warning, and critical statuses. To generate an A ...

Tips for locating a file using javascript

My application scans a folder and displays all folders and HTML files inside it in a dropdown menu. It also shows any HTML files inside an iframe. There is one file named "highlighted.html" that should not appear in the dropdown menu, but if it exists in t ...

AngularJS has the ability to handle the value of one input based on the value of another input

How can I ensure that if one input has a value, the other must also be filled in AngularJS? I'm looking for the best approach to handle this requirement in an angular way. Any suggestions? Below is my code: <div class="form-group recipe_item" ng ...

Developing a single page that caters to various users' needs

Greetings to all my friends, As a front end developer, I am in the process of implementing a dashboard for a project that involves different users with varying permissions. Each user should only have access to certain parts of the page, resulting in some ...

`Where to include controller.js scripts in an Angular application`

As I dive into learning angular.js with .NET MVC, one major issue that keeps coming up is the fact that many tutorials advise referencing multiple controllers and services in the main (_Layout) page, which can make it quite messy. Although it may seem sim ...

Ensuring the accuracy of user input

Can someone assist me with comparing two dates in JSP? I need validation that alerts the user when a future date is entered. The start date or end date should not be in the future. The date format is 12-5-2011 10:51:49. Any help would be greatly apprecia ...

The functionality of JQuery stops functioning once ajax (Node.js, PUG) is integrated

I've been attempting to incorporate a like feature on my blog post website. When I click on the likes count, it's supposed to trigger an ajax call. In my server.js file, there's a function that handles the POST request to update the number ...

Utilizing JavaScript to display numerous variables within a text box

After creating an HTML form, I encountered an issue where only one selected item was displayed in the text field. Can anyone help me solve this problem so that multiple names can be printed in the textfield? function myFun(extras) { document.get ...

When the app loads in AngularJS, make sure to call the jQuery plugin. Additionally, remember to call

In my AngularJS app, I have a need to call the following code: $('.nano').nanoScroller({ alwaysVisible: true }); This should be executed when the application loads and also when the state changes. In traditional non-angular applications, I wou ...

Consecutive POST requests in Angular 4

Can you assist me with making sequential (synchronous) http POST calls that wait for the response from each call? generateDoc(project, Item, language, isDOCXFormat) : Observable<any> { return this.http.post(this.sessionStorageService.retriev ...

duplicate styling for individual table cells

I am in need of a span element inside a td tag that I am generating within a table. In order to ensure the span fills the td, I have set it as an inline-block with a width and height of 100%. However, when pressing the delete key in the last cell, it star ...

The setTimeout function appears to be malfunctioning

I've encountered an issue where a webpage keeps scrolling endlessly without stopping. I've attempted to terminate it by using the exit function, but unfortunately it's not working. Does anyone have a solution for this problem? ...

sending an array from one CodeIgniter view to another view via Ajax

In the following code segments of my application, myArray is an array where each element contains a few objects that I need to use in a second view. When I use alert(myJSON);, I am able to see the array in the alert window. However, when the view loads, i ...

Adding dynamic elements to a pop-up window with the use of jQuery's .load() function

When implementing Javascript to create a modal, I have encountered an issue where the close button disappears. The modal opens and loads different HTML files dynamically using the jQuery load() method, but the close button vanishes. I suspect that the mod ...

Transferring data only once specific agreements have been fulfilled

Imagine having a file with specific promises that, when executed sequentially, create an input file called input.txt. // prepareInput.js var step1 = function() { var promise = new Promise(function(resolve, reject) { ... }); return p ...

What is the most effective method for inputting a date/time into a Django view?

Looking to create a feature where users can see what events are happening at a specific time. What is the most efficient method to implement this request? For example, if I want to display all current events, should I submit a post request to /events/2009 ...