Created
May 19, 2015 08:06
-
-
Save davidallsopp/926f6cdc747b6e40e000 to your computer and use it in GitHub Desktop.
Animating HTML divs using D3 transitions and relative/absolute positioning
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<body> | |
<script src="http://d3js.org/d3.v3.min.js"></script> | |
<style> | |
.spacer { | |
height: 50px; /* Just to confirm our positions are relative to the event list not the window */ | |
} | |
#event-list { | |
position: relative; /* or absolute - just not static! */ | |
width: 500px; | |
height: 600px; | |
background: #eeeeee; | |
padding: 4px; | |
} | |
.event { | |
margin: 4px; | |
padding: 6px; | |
} | |
.event-title { | |
font-size: 1.5em; | |
font-weight: bold; | |
} | |
.event-info { | |
font-size: 1em; | |
} | |
</style> | |
<div class="spacer"></div> | |
<div id="event-list"> | |
</div> | |
<script> | |
var data = [{name:"Event1", text: "First event", timestamp: 1}, | |
{name:"Event2", text: "Second event", timestamp: 2}, | |
{name:"Event3", text: "Third event", timestamp: 3} | |
]; | |
var key = function(x) { return x.timestamp; }; | |
var events = d3.select("#event-list").selectAll("div") | |
.data(data,key) | |
events.enter().append("div") | |
.attr("class", "event") | |
.style("position", "absolute") | |
.style("top", "1000px") | |
.style("height", 100) | |
.style("width", "94%") | |
.style("background-color", "#ff0") | |
.style("color", "#eee") | |
.transition().duration(function(d, i) { return (i+1) * 750; }) | |
.style("background-color", "#fff") | |
.style("color", "#000") | |
.style("top", function(d, i) { return (i * 110)+"px"; }) | |
events.append("h3").text(function(d) { return d.name; }); | |
events.append("p").text(function(d) { return d.text; }); | |
</script> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment