Stone Stone -3 years ago 133
Javascript Question

How to reload div using d3.js library

How to reload a div create with d3.js?

I have this function in my js file

$(document).ready(function(){
calculateStatic();

setInterval(function(){
calculateStatic();
}, 5000);

});


The function call every 5 second but the
div
don't change, my code to create a div is like that

function calculateStatic(){
var json_url = "....";
var dataset_text = [
{"sSUSP" : "number of suspended slots",
"sRSV" : "number of reserved slots",
"users" : "number of active users",
"jPEND" : "number of pending jobs",
"queues" : "number of active queues",
"sRUN" : "number of running slots",
"jRUN" : "number of running jobs",
"ts": "Current time",
"sNJOBS" : "total number of active slots"}
];
var final_data = [];

d3.json(json_url, function(data) {
$.each(data, function(key, value){
if (key in dataset_text[0]){
name = dataset_text[0][key]
final_data.push({name, value});
}
});
d3.select("#resume_data").selectAll("div")
.data(final_data)
.enter()
.append("div")
.attr("class", "item_table")
.text(function(d){ return d.name + " : " + d.value})
});
}


any idea how to change this
div
?

Answer Source

Analysing you code, we can see that final_data length is never getting bigger. Thus, this is the problem: when you bind the data like this:

d3.select("#resume_data").selectAll("div")
    .data(final_data)
    .enter()
    .append("div")

You create an "enter" selection. But, when you call the function again, as you already have <div>s in #resume_data and your bound data is never increasing, your "enter" selection is always empty, and nothing is appended.

The proper solution is, as @Pavel said in the comments, create a proper "update" selection.

Lazy solution:

This is a lazy solution, which I personally don't like at all: remove all the previous divs before appending the new ones:

d3.select("#resume_data").selectAll("div").remove();//removing old divs

d3.select("#resume_data").selectAll("div")
    .data(final_data)
    .enter()
    .append("div")
    .attr("class", "item_table")
    .text(function(d){ return d.name + " : " + d.value});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download