Issue with appending SVG elements in HTML

In my application, I am utilizing d3js charts as widgets. When a widget is added, a function is triggered to create and draw the widget (svg element) in a specific div.

The issue arises when the same widget is added twice, causing the d3js chart (svg element) to be appended to the previously created div instead of creating a new one. Additionally, I am encountering difficulties in resizing the charts when the div is resized.

Here is the AJAX response:

<div id="chart"></div>
<script>
var m = [30, 50, 10, 30],
w = 600 - m[1] - m[3],
h = 400 - m[0] - m[2];

var format = d3.format(",.0f");

var x = d3.scale.linear().range([0, w]),
y = d3.scale.ordinal().rangeRoundBands([0, h], .1);

var xAxis = d3.svg.axis().scale(x).orient("top").tickSize(-h),
yAxis = d3.svg.axis().scale(y).orient("left").tickSize(0);

var svg = d3.select("#chart").append("svg")
.attr("width", w + m[1] + m[3])
.attr("height", h + m[0] + m[2])
.attr("viewBox", "0 0 600 400")
.append("g")
.attr("transform", "translate(" + m[3] + "," + m[0] + ")")

 // Parsing numbers and sorting by value.
data.forEach(function(d) { d.value = +d.value; });
data.sort(function(a, b) { return b.value - a.value; });

// Setting scale domain.
x.domain([0, d3.max(data, function(d) { return d.value; })]);
y.domain(data.map(function(d) { return d.name; }));

var bar = svg.selectAll("g.bar")
.data(data)
.enter().append("g")
.attr("class", "bar")
.attr("transform", function(d) { return "translate(0," + y(d.name) + ")"; });

bar.append("rect")
.attr("width", function(d) { return x(d.value); })
.attr("height", y.rangeBand());

bar.append("text")
.attr("class", "value")
.attr("x", function(d) { return x(d.value); })
.attr("y", y.rangeBand() / 2)
.attr("dx", 50)
.attr("dy", ".35em")
.attr("text-anchor", "end")
.text(function(d) { return format(d.value); });

svg.append("g")
.attr("class", "x axis")
.call(xAxis);

svg.append("g")
.attr("class", "y axis")
.call(yAxis);
</script>

This code snippet is being appended:

 var i = counter;

$('<div class=\"box\" >'+ response +'</div>').appendTo("#data-"+i); 

Below is a cropped image depicting the issue:

Answer №1

It appears that the main issue you are facing is with reusing the id attributes in your code. Having multiple instances of

<div id="chart"></div>
on a single page can cause conflicts since ids should be unique.

When you use d3.select("#chart"), it will target the same div element every time. This could result in selecting either the first or last occurrence of that element on the page, depending on the browser.

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

Steps for creating checkboxes for individual table rows in HTML using embedded PHP and updating their values in a PostgreSQL database:1. Begin by iterating through each

I have already retrieved the data from the database. It is displayed on the HTML table, but it is currently in non-editable mode. I need to ensure that the data shown is accurate and update its Boolean value in the database. Otherwise, incorrect records sh ...

Choosing the best option among various cells within a table

How can jQuery be used to specifically target all the TR elements with only 2 TD inside? Here is an example scenario: <table> <tr> <td></td> </tr> <tr> /* This row should be the only one selec ...

Fluid Grid design showcasing a gap on the right side

After working on the Skeleton Framework and making adjustments to the grid design, I am facing a small gap issue on the right side. Despite things slowly falling into place, this minor gap is causing confusion. Please refer to the image below for clarifica ...

Troubleshooting undefined index issue when retrieving data from database (related to Ajax functionality)

Despite following the instructions on w3schools, I am struggling to get the script to return the desired data when selecting a user from the dropdown menu. Instead, I keep receiving an error message stating "undefined index: userdrop". Could changing GET t ...

Calculate the factorial of a number by leveraging the power of arrays in Javascript

I attempted to create a function that accepts a parameter and populates an array with numbers less than the parameter down to zero in descending order. I then used a for loop to multiply each element in the array by the next element, but unfortunately, m ...

I am facing an issue with effectively passing properties from a parent state to its child component

In the Login component, I set the authentication state using the token as false initially. After a successful login, the token is changed to true. function Login() { const [user, setUser] = useState({ name: '', email: '' }); const [ ...

Transform JSON data into HTML format while excluding particular values

I recently integrated a JSON API that fetches event data. Here's a snippet of the JSON structure: { "id":1, "status":"ok", "start":{ "date":"2021-01-16" } } To display this ...

Controlling MYSQL data is not possible

When I retrieve data from the database, everything is functioning correctly, but the data flow seems uncontrolled. Here is a snippet of my code... <?php session_start(); include 'conn.php'; include '../includes/layouts/header.php'; ...

Modifying the Nav-Bar background color causes the hamburger icon to become invisible

Here's the code I'm working with: <nav class="navbar navbar-expand-lg navbar-md-dark navbar-lg-light" style="background-color: #11100b;" id="nav-mob"> <div class="container"> <a ...

The error message thrown in Node.js: "Cannot access 'filename' property of undefined object"

Struggling with an issue in nodejs, whenever I try to post with an image, I keep getting the error message "Cannot read property 'filename' of undefined" I've been trying to debug but can't find the root cause of the error. Can someone ...

Display alternative text dynamically

Trying to gain a deeper understanding of state in react, this is a perfect example to me. When I say dynamic, I mean displaying the output below instantly as it is entered in the form. class Demo extends Component { constructor(props) { super ...

What is the best way to make an animated image move?

Seeking guidance on how to achieve a particular effect like the one showcased at I'm specifically interested in replicating the block movement upon hover and the change in block coordinates when the cursor is not active. Does anyone know of a suitabl ...

The asp:Button with a fixed/absolute position is unresponsive in both Firefox and Google Chrome, making it un

I am currently coding in ASP.NET. I have a button that is clickable on Internet Explorer but not on Firefox or Google Chrome. After investigating, I found out that the issue lies in its CSS property being set to position: absoulute OR position:fixed. Her ...

Modifying the color of a div based on a specified value using JavaScript

<div id="navigation"> Add your text here </div> <input type="text" id="newColor"><button onclick="modifyColor()">Update</button> <script> function modifyColor(){ var chosenColor = document.getElementB ...

Trouble arises when implementing a nested flex layout in Angular Material shorthand

I'm having trouble identifying the issue with this particular layout. My goal is to maintain a Single Page Application layout where the "deepest" component only becomes scrollable if the viewport height is too small, as indicated in the snippet by us ...

Ways to perfectly align objects in a container without compromising the height of the parent element

Within my container div, I have two spans. An issue arises when I attempt to align the items to the center using align-items: center, as this causes the spans to lose their defined height and border-radius properties. My goal is to keep the heights and bor ...

Performing a double running of an Express GET request with an :id parameter

I'm working on an API using node and express, where the main aim is to capture the :id parameter from the request and store it in a variable. This will allow me to query a specific table in my SQLite database based on that particular id. However, I am ...

Adjust the height of Revolution Slider on mobile devices using initialization

To see an example of the Revolution Slider, please check out the top hero section on this page. If you are looking for the initialization code, you can find it in this javascript file: function dz_rev_slider_5(){ if(dzQuery("#rev_slider_11_1" ...

What are the steps to validate an Ajax form using Dojo JavaScript?

Currently, I am in the process of validating a form that has been written in Javascript/Dojo before sending it via Ajax. Here is the code snippet: <script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojo/dojo.xd.js" type="text/javascript" djConf ...

When a user hovers over the image, a button is revealed

I have a test page on my website: If you'd like to check it out, feel free to visit: I am trying to create a feature where when you hover over an image, a black button with text and links will appear. When you move your mouse away from the image, ...