HTML/SVG elements that have just been created are known as entering elements and ones that are about to be removed are known as exiting elements.
You can treat entering and exiting elements differently by passing functions into the .join
method :
.join(
function(enter) {
...
},
function(update) {
...
},
function(exit) {
...
}
)
The first, second and third functions are named the enter, update and exit functions, respectively.
Each function has a single parameter::
* the enter function’s parameter enter is the enter selection which represents the elements that need to be created
* the update function’s parameter update is a selection containing the elements that are already in existence (and aren’t exiting)
* the exit function’s parameter exit is the exit selection and contains elements that need to to be removed
The .join
method returns a selection containing the entering and existing elements (it doesn’t contain exiting elements). Typically most of your style and attribute updates will follow the .join
method.
Note that the enter, update and exit functions must return the selection.
Enter function : In general the enter function must append an element to each element of the enter selection. (The enter selection consists of ‘placeholder’ elements that represent the elements that need to be added.)
For example :
.join(
function(enter) {
return enter.append('circle');
}
)
This is equivalent to .join('circle')
.
You can also call the usual selection methods such as .style
and .attr
on the enter selection. This allows you to modify style and attributes of the entering elements.
For example :
.join(
function(enter) {
return enter
.append('circle')
.style('opacity', 0);
}
)
Update function : The update function is optional and lets you update elements that are already in existence. For example:
.join(
function(enter) {
return enter
.append('circle')
.style('opacity', 0);
},
function(update) {
return update.style('opacity', 1);
}
)
This will set the opacity of entering circles to zero and the opacity of existing circles to 1.
Exit function : The exit function is optional and handles HTML/SVG elements that need to be removed. In general you need to remove the elements in the exit selection:
.join(
function(enter) {
return enter
.append('circle')
.style('opacity', 0);
},
function(update) {
return update
.style('opacity', 1);
},
function(exit) {
return exit.remove();
}
)