# Enter update exit

#### d3_enter_update_exit.html ● d3.min.js ● data/fruit.csv

### About

Deleting and recreating visual elements on any change is expensive. That is one reason why D3 provides the Enter – Update – Exit pattern. As you have already heard D3 provides the method enter(), and there is also the exit()-function. Both control the interaction between data and HTML elements it is bound to.
Let's recap:

- mySelection.data(data).enter() handles data items for which no elements exist yet in the selec- tion. Often we want to append missing elements here.
- mySelection.data(data).exit() handles elements for which no data item exists in our selection anymore. Often we want to remove the superfluous elements here.
- mySelection.data(data) only binding data and elements returns the 'update' selection and handles existing elements for which the data changed. Often here most things are done, e.g. setting the element's properties.

Source

### Example

To see how the enter update exit pattern works, we now want to color all fruits green, which are new, and all updated ones red. All exit-elements should be removed. Then we want to merge the enter and update elements and add them a black border.

First we have to select the fruits from before and bind the new data to it. Here it is very important that we set a key as second parameter, which D3 needs to identify and compare the objects.

let fruitsUpdate = diagram.selectAll("circle")
.data(newData, d => d.name)

Then we have to define the enter, merge and exit selections.

let fruitsEnter = fruitsUpdate.enter()
.append("circle")
let fruitsMerge = fruitsUpdate.merge(fruitsEnter)
let fruitsExit = fruitsUpdate.exit()

And then we can add all the changes for the elements:

fruitsEnter
.attr("fill","green")
fruitsMerge
.attr("cy",100)
.attr("cx",(d,i) => scaleX(d.weight))
.attr("r", d => d.size)
.attr("stroke-width","2")
.attr("stroke","black")
.on("mouseover",fruitOver)
.on("mouseout",fruitOut)
fruitsUpdate
.attr("fill","red")
fruitsExit.remove();

So now take a look at what happens, when you change the data:

### More about interaction TODO

- JS events on w3schools
- List of all DOM events