# Transitions from one element to another

I am implementing an automated help function in my code. It is simply a few bubbles that pop up with some text in them. I use d3 to select one bubble, display it for a short time, and then select another bubble and display that one. It works, but I don't like the shape the code is taking. Am I approaching this correctly?

d3.select("#targetYear-bubble")
.transition().duration(2000)
.style("opacity", 1)
.transition().duration(2000)
.style("opacity", 0)
.each("end", function()
{
d3.select("#navTree-bubble").transition().duration(2000)
.style("opacity", 1)
.transition().duration(2000)
.style("opacity", 0);
})
;


This code displays 2 pop-up bubbles. It's manageable for now, but if I had a complex screen with 7 or 8 (or more) bubbles, this code would be much too complex.

Can someone make a suggestion for a better implementation of this?

• Welcome to Code Review. Your first question has been reviewed and accepted. I expect that you'll get a number of useful reviews. – Edward Apr 8 '15 at 13:46

Yes, if you chain with each then its has to be a recursive structure like that.

I like the mediator pattern for this...

var mediator = d3.dispatch('phase1', 'phase2'),

bubbles = d3.selectAll(".bubbles")
.style("opacity", 0.5);

mediator.on('phase1', function(then) {

d3.select(".bubble1")
.transition().duration(2000)
.style("opacity", 1)
.transition().duration(2000)
.style("opacity", 0)
.each('end.phase1', function () { mediator[then]() })

});

mediator.on('phase2', function() {

d3.select(".bubble2")
.transition().duration(2000)
.style("opacity", 1)
.transition().duration(2000)
.style("opacity", 0);

});

mediator.phase1('phase2');
<div class="bubbles bubble1">bubble1</div>
<div class="bubbles bubble2">bubble2</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

It's much easier to automate

• Nice. I Used your suggestion and the code is instantly easier to maintain and grow. I did, however, leave out the line that selects all ".bubbles" in the beginning. No need for it that I can see. – user69894 Apr 8 '15 at 17:01
• Yes, its much easier to understand but still declarative and data-driven and the coupling is simpler. The first selection was just there so that I could style the divs so I could see them for test purposes. I don't like seeing a blank page when it loads... d3 is already scary enough without that! – Cool Blue Apr 8 '15 at 18:01