Incorporate Additional Rows into Grid Layout using d3

Being relatively new to d3, I have been struggling with understanding data joins. My current challenge involves adding rows to a grid layout, where each row is represented as an object with multiple slots stored in an array.

Within my .join, I am attempting to add multiple elements to the selection (with content based on the slots of the object, specifically the .text). However, I am facing difficulties in specifying the .selectAll call prior to the .data call. I realize why this behavior is occurring – it tries to match the data with all divs in the selection (which are essentially all cells).

How should I modify my code so that each button click simply adds a new row?

Additionally, how can I ensure that the cells are added by row and not by column?

const data = [
  {cell1: '1/1', cell2: '1/2', cell3: '1/3', id: 1},
  {cell1: '2/1', cell2: '2/2', cell3: '2/3', id: 2}
];


function update(data) {
  d3.select('#grid')
    .selectAll('div')
    .data(data, (d) => d.id)
    .join((enter) => {
      enter.append('div')
        .classed('cell1', true)
        .text((d) => d.cell1);
      enter.append('div')
        .classed('cell2', true)
        .text((d) => d.cell2)
      enter.append('div')
        .classed('cell3', true)
        .text((d) => d.cell3);
  })
}

update(data)

function addRow() {
  const n = data.length + 1;
  const newRow = {cell1: n + '/1', cell2: n + '/2', cell3: n + '/3', id: n};
  data.push(newRow);
  update(data);
}
#grid {
  display: inline-grid;
  grid-template-columns: repeat(3, 200px);
}

#grid > div:nth-of-type(3n+2) {
  background-color: orange;
}

#grid > div:nth-of-type(3n+1) {
  background-color: purple;
}


#grid > div:nth-of-type(3n+0) {
  background-color: forestgreen;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.8.5/d3.min.js"></script>
<div id="grid">
</div>
<button id="add" onclick="addRow()">Add Row</button>

Answer №1

The initial issue has been resolved successfully. It was discovered that calling .selectAll with 'div' selected all divs in the selection, causing a mismatch of rows when paired with n rows and n x 3 divs.

An easy solution is to specifically select only the first div using .selectAll('.cell1'). This ensures that there is always a correlation between data rows and grid rows, given that each row contains a single div with the class cell1.

The only remaining challenge is the disorder of the order, which will be addressed in a separate question.

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 the sliding navigation glitching due to the video background?

Currently, I am in the process of developing a website with a captivating full-page video background. The nav menu gracefully slides out from the left side using jQuery UI when users scroll down to view the site's content. To view the work-in-progres ...

A guide to accessing real-time data in Vue.js

This is my debut project in Vue, and I am currently retrieving cart data from the server. My goal is to be able to modify the quantity using Vue. Right now, when I click on the up or down arrow to change the quantity, it gets reflected in the server databa ...

Seeking out and upgrading essential information: how to do it effectively?

I am working with a document in a mongo collection that looks like this: { "_id" :"sdsfsfd323323323ssd", "data" : { "('State', 'Get-Alert', 'BLIST_1', 'MessageData')" : [ "$B_Add-Server", ...

What is the best way to clear the values of multiple chosen-select boxes in one go?

I am encountering an issue while using a chosen-select plugin. I have multiple select boxes created with JavaScript code. My goal is to reset all select boxes when I change the class to "default-chosen", but instead of displaying my message "not chosen," i ...

Encountered a 404 Error when attempting to store data in mongoDb using node.js and express

Currently, I am facing an issue while trying to save data from Bootstrap input fields into my MongoDB database. Every time I attempt to do so, I encounter the error insertMovie:1 POST http://localhost:3000/insertMovie 404 (Not Found). Despite my efforts to ...

Ways to eliminate the initial digit of a decimal number if it is less than 1

I need assistance with modifying float values by removing the first number if it's lower than 1 In the "OPS" table section, I am calculating the sum of OBP and SLG obtained from a database. https://i.sstatic.net/cYwwW.jpg See the code snippet below ...

Execute a JavaScript code to run a Selenium Webdriver script

Is it possible to execute a selenium webdriver script, written in Eclipse, by using JavaScript code to click on an HTML button? I am looking for any ideas or suggestions on how to run the Selenium script. Thanks! ...

What is the best way to display a nested JSON object structure?

{ "Title": "Jurassic Park", "Year": "1993", "Rated": "PG-13", "Released": "11 Jun 1993", "Runtime": "127 min", "Genre": "Action, Adventure, Sci-Fi", "Director": "Steven Spielberg", "Writer": "Michael Crichton, David Koepp", "Actors": "Sam ...

Ways to incorporate horizontal scrolling into a flex container within a Bootstrap navigation bar

I am encountering an issue with my Bootstrap navigation menu that uses a flex container (). The goal is to have horizontal scrolling for the menu items when they surpass the width of the container. I have implemented the following CSS style on the containe ...

Creating HTML email content in PHP by merging long strings

I am currently working on a project that involves receiving a JSON webhook and using it to send email notifications. While I have successfully sorted the JSON data, I am unsure of how to create a large HTML email. It seems that attempting to use an If sta ...

Can a low-opacity gradient be merged with a solid background color?

Can anyone help with this code snippet? Here's the link table { height: 200px; width: 200px; background-color: #444557; /* seems to be hidden by the gradient */ /* Here is the CSS for a gradient background */ /* Source: http://colorzilla ...

Is it possible to implement the onscroll function from jQuery in Vue.js?

I am looking to implement a sticky navbar feature using JQuery on scroll function in vue.js. Can anyone guide me on how to achieve this seamlessly? Currently, I have my Components set up as a bootstrap navbar that I want to stick onscroll. If there are al ...

Prioritize the Menu display

Is there a way to bring the menu's black background in front of the body text in the image below? Here is the JSFiddle link for reference: https://jsfiddle.net/johnking/j58cubux/6/ The issue occurs when scrolling down and the menu is not clearly vi ...

Utilizing React for incorporating HTML5 canvas gradients

I'm currently working on an app that allows users to generate a background gradient with two distinct colors using React. The issue I'm facing is that while the first color appears correctly, the second color ends up looking more like a solid col ...

What is the best way to make the Bootstrap navbar stay fixed at the top of the

I am currently experiencing an issue with the Bootstrap navbar while using version 5.0. Whenever the Bootstrap navbar expands, the content below it also moves down, which is not the desired behavior. I want the content to remain in place. I tried set ...

Parsing JSON data in JavaScript to extract multiple records and store them in individual variables in memory

Although I have utilized JSON stringify and JSON Parse before, I am currently struggling to split up my JSON result into multiple variables. Challenge: My JSON result contains multiple sections or pages, and my objective is to store each of these results ...

Introducing a pause in the function while rendering objects

After inserting setInterval into the code, it is causing all lasers to be delayed by one second. I am looking to have them fired in this order: - initially fire laser1 and laser2. - then take a 1-second break before firing another set of lasers, a ...

In jQuery, how to create a single event that applies to two different elements simultaneously, rather than individually for each element

How can I create a toggle event for 2 different TDs within my table row that will show/hide the next table row when clicked? <table> <tr> <td>1</td> <td>2</td> <td>3</td> <td>4</td> & ...

Stop images from being stored in the database instead of text characters

Using a proxy, I attempt to parse some HTML. One of the elements is retrieved using jQuery: var site = 'http://www.kartabu.com/pl/index.php?filter=random' var url = 'http://localhost/taboo.blue-world.pl/admin/proxy.php?url=' + encodeUR ...

In Bootstrap 5, clicking inside a dropdown should not cause it to open or close unexpectedly

Check out the code snippet below: <html> <head> <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7d1f1212090e090f1c0d3d48534e534e">[email protected]</a>/d ...