Skip to content

Instantly share code, notes, and snippets.

@BMPMS
Last active May 16, 2018 10:21
Show Gist options
  • Save BMPMS/21ca3ca9671e93b57bee831ff2e0e99d to your computer and use it in GitHub Desktop.
Save BMPMS/21ca3ca9671e93b57bee831ff2e0e99d to your computer and use it in GitHub Desktop.
D3 v4 Merge - demo key and no key
<!DOCTYPE html>
<meta charset="utf-8">
<head>
<title>Merge with and without Key</title>
</head>
<style>
body {
font-family: "Helvetica Neue", Helvetica, sans-serif;
font-size: 14px;
color: #333;
}
#menu {
height: 40px;
}
.no_key_div, .key_div {
margin: 2px;
color: white;
padding: 8px;
width: 14px;
height: 14px;
text-align: center;
position: absolute;
}
.key_div {
background-color: blue;
top:20px;
}
.no_key_div {
background-color: orange;
top:50px;
}
#key, #key_div {
position: relative;
height: 40px;
}
</style>
<body>
<div id="menu"><button onClick="doUpdate();">Update</button></div>
<div id="no_key">NO KEY<br>
(data 'rebound' to all elements) </div>
<div id="key"><br>KEY<br>(data bound to same element)</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script>
<script>
var letter_list = ["ABCDEF","GHIJKXYZ","ACDGHIJKLYZ","EFMXYZ","LMNOP","ABC"];
var position = 0;
function doUpdate() {
//loop through data and call both functions
if(position <= letter_list.length){
update_no_key(letter_list[position]);
update_key(letter_list[position])
position += 1;
if(position == letter_list.length){
position = 0;
}
}
}
function update_no_key(data) {
//data join
var u = d3.select('#no_key')
.selectAll('.no_key_div')
.data(data)
.attr("class","no_key_div");
//enter, append new data and merge with old
u.enter()
.append('div')
.attr("class","no_key_div")
.merge(u)
.style('left', function(d, i) {
return 260 + (i * 34) + 'px';
})
.text(function(d) {return d;});
//remove redundant divs (if they exist)
u.exit().remove();
}
function update_key(data) {
var u = d3.select('#key')
.selectAll('.key_div')
.data(data,function(d){return d})
.attr("class","key_div");
u.enter()
.append('div')
.attr("class","key_div")
.merge(u)
.transition()
.style('left', function(d, i) {
return 254 + (i * 34) + 'px';
})
.text(function(d) {
return d;
});
u.exit().remove();
}
doUpdate();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment