# Interaction

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

### About

Until now our visualizations do not allow any user interaction. Since interaction is an integral building block of most recent visualizations we will now take a glance at simple ways to integrate this in our page.

### HTML GUI elements

Probably the simplest form of adding interactivity to your visualization is providing HTML GUI elements that call JavaScript functions, which, in turn, manipulate the visual elements.

### Example

For example, we can create a button that calls the function onButtonClick(). Then the function selects the title and changes it name to "No vegetables"

<button onclick="onButtonClick()">Run</button>
<script>
function onButtonClick(){
d3.select("#title").text("No vegetables")
}
</script>

### Interaction in the visualisation

For sure we are also able to add interactivity to our visualisation. Now we want to display the name of the fruits, if the cursor moves over the fruit. Therefore we have the on-function, which we need to add to the fruits:

.on("mouseover",fruitOver)

Then we have to define the corresponding function. We implicitly get two parameters, the first on is the event, which is fired by the mouseover, the second one is the element, over which we hovered.

function fruitOver(event, d){
d3.select(#diagram).append("text")
.text(d.name)
.attr("x", scaleX(d.weight) - 20)
.attr("y", 100 - d.size - 10)
.attr("id", "fruitName")
}

And now, we also have to delete the element, when the cursor leaves the fruit-circle. The event we need is called "mouseout" and in the function it is the easiest way to select the created element by it's id and use the remove()-function.

.on("mouseout",fruitOut)
function fruitOut(event, d){
d3.select("#fruitName").remove();
}

Take a look, it works:

### More about interaction

- More about the .on()-function
- JS events on w3schools
- List of all DOM events