Skip to content

Embed D3.js Animations in Slidify

Olivia Burge edited this page Oct 14, 2016 · 3 revisions

Recently, a question was posted asking if it was possible to postpone execution of a script till a particular slide was reached. The context was that the user wanted to embed a d3.js animation in a slide. I suggested using iframes and adding the following code to the slide

<iframe src="http://bl.ocks.org/mbostock/raw/1256572/"></iframe>

This would embed the animation, but the start was triggered as soon as the slide deck was opened. The solution was to add the iframe to the slide deck only after we enter the slide on which it was displayed. Digging through the code for the Google IO 2012 framework (which is the default for Slidify), I realized that I could make use of two events slideenter and slideleave which are triggered when we enter/leave a slide.

This idea resulted in the following slide. The key was to append the iframe to the slide when it is entered and remove it when we leave the slide. As a result, the animation would be triggered from the start every time we enter this slide. You can preview the effect here

--- #myslide

<script>
$('#myslide').on('slideenter', function(){
  $(this).find('article')
    .append('<iframe src="http://bl.ocks.org/mbostock/raw/1256572/"></iframe>')
});
$('#myslide').on('slideleave', function(){
  $(this).find('iframe').remove();
});
</script>

Update (14/10/16): using bl.ocks.org no longer works for embedding d3 in slidify - see issue and solution here

Clone this wiki locally