Skip to content

Instantly share code, notes, and snippets.

@jsoma
Created April 8, 2022 13:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsoma/5eb2134277146ef854f91044b001b358 to your computer and use it in GitHub Desktop.
Save jsoma/5eb2134277146ef854f91044b001b358 to your computer and use it in GitHub Desktop.
Use D3/JavaScript with ai2html: animating (and un-animating)

Maybe you styled a map in illustrator to look a certain way - the markers all have nice unique colors, opacity, etc etc. And then you plugged it into your scrollytelling piece: looking good so far.

On step 2 of your piece you want to change those markers: make them all yellow! Highlight them! #FFF880 is my favorite yellow highlight color. That's fine, normally you'd just do this to transition to the highlight color:

d3.selectAll("[data-name='africa'] path")
    .transition()
    .attr('fill', '#FFF880')

There's a problem, though: when you get to step 3 (or if you scroll back up) you want to change the markers back to their original color. Since of the markers weren't originally all the same color you can't just do .attr('fill', 'blue'). How can you get the original colors back?

Here's how to change those ai2html attributes with JavaScript (and change back later)

When you load the page, create a new attribute called data-original-fill on each of the circles, setting it to the value of fill (the current color of the circle). This is me targeting all of the paths inside of the africa group, like from the original ai2html scrollytelling tutorial.

d3.selectAll("[data-name='africa'] path")
    .attr('data-original-fill', d => this.getAttribute('fill'))

Then in a step somewhere, I'll make them all yellow to highlight them.

d3.selectAll("[data-name='africa' path")
    .transition()
    .attr('fill', '#FFF880')

Then when I leave the step, I'll return their fill to the original color. We're updating the fill attribute with whatever was in the data-original-fill attribute.

d3.selectAll("[data-name='africa' path")
   .transition()
   .attr('fill', d => this.getAttribute('data-original-fill'))

The markers return to their original color, everything works, rainbows shoot out of the computer, unicorns bless you from the heavens, etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment