D3-js[Data handling]
Local server hosting
Open a new terminal in Mac
cd ~/Desktop/project-folder
python -m SimpleHTTPServer 8888 &.filename
Chaining
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset = "utf-8">
<title> D3 Page Template</title>
<script type="text/javascript" src="d3.js"></script>
</head>
<body>
<script type="text/javascript">
d3.select("body").append("p").text("New paragraph!");
</script>
</body>
</html>
d3: Refer the D3 object.
.select("body"): Give the select() method a CSS selector as input
append("p"): empty p paragraph is appended to the body.
.text("New paragraph!")
Handoff: D3 methods return a selection (So it uses chaining)
Without chaining we can also re-paragraph above code.
Binding data
csv(): the path, call back function
When the call back function is called, the csv file is already imported. Every value in csv is stored as a string, even the number. So converting is needed. While the csv fild is loaded, the rest of a code is executed so assigning global variable would be helpful.
Selection
We have to select elements that don't yet exist. The magical method is "enter"
d3.select("body"): Finds the body in the DOM
.selectAll("p"): Selects all paragraphs in the DOM. This returns an empty selection because none exist yet.
.data(dataset): Counts and parses our data values.
enter(): Creates a new placeholder element
.append("p"): appends a p element
.text("New paragraph!"): inserts a text value into p
If we use .text(function(d) { return d; }); it populates the contents of each paragraph from our data.
Functioning
Div and Attr
div needs to be assigned the bar class. To add a class to an element, we use the attr() method. (not style()) style() applies CSS styles directly to an element.
Attribute
Value
class
caption
id
country
src
logo.png
width
100px
alt
Logo
To assign a class of bar we can use: .attr("class","bar")
Classes
Element's class is stored as an HTML attribute.
Last updated
Was this helpful?