Skip to content

Instantly share code, notes, and snippets.

@erkal
Last active August 29, 2015 13:57
Show Gist options
  • Save erkal/9871048 to your computer and use it in GitHub Desktop.
Save erkal/9871048 to your computer and use it in GitHub Desktop.
playButton

playButton

Here is a simple mechanism mainly for the purpose of building step by step illustrations in bl.ocks.org.

It is better compared to using setTimeouts, because

  • it gives the control to the user,
  • it saves you time because you don't need to worry about the optimum time intervals.

The function playButton takes as arguments an svg element svg, a function list fnList and coordinates x & y. It appends a play button into svg, which on mousedown event, evaluates the functions in fnList one by one.

playButton uses a scoped variable i to store its state.

On mouseover, you can see the function that play button is going to evaluate next.

playButton removes it self, when the end of fnList is reached.

An example usage is here: General Update Pattern with playButton

<!DOCTYPE html>
<meta charset="utf-8">
<title>playButton</title>
<style>
#messageText{
font-size: 60px;
text-anchor: middle;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
// ----------------------------------------------------------------------
var width = 960,
height = 500;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var messageText = svg.append("text")
.attr("id", "messageText")
.attr("x", width/2)
.attr("y", 200);
write("click the play button");
var fnList = [
function() { write("again"); },
function() { write("and again"); },
function() { write("see?"); },
function() { write("you cannot click any more"); }
]
playButton(svg, fnList, width/2 -25 , 300);
function write(text) { messageText.attr("class", text).text(text) }
function playButton(svg, fnList, x, y) {
var i = 0;
var button = svg.append("g")
.attr("transform", "translate("+ x +","+ y +")");
button
.append("rect")
.attr("width", 50)
.attr("height", 50)
.attr("rx", 4)
.style("fill", "steelblue");
button
.append("path")
.attr("d", "M15 10 L15 40 L35 25 Z")
.style("fill", "white");
button
.append("title")
.text(String(fnList[0]));
button
.on("mousedown", function() {
d3.select(this).select("rect")
.style("fill","white")
.transition().style("fill","steelblue");
fnList[i]();
i++;
d3.select(this).select("title").text(String(fnList[i]));
if (i == fnList.length) d3.select(this).remove();
});
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment