Dynamically dispatch interactions
In this tutorial, we will learn how you can dynamically dispatch a highlight behaviour on selecting data values from dropdown.
Create a chart
First, we will create a chart with a x-axis as Cylinders and y-axis as Horsepower.
const { muze, getDataFromSearchQuery } = viz;
const data = getDataFromSearchQuery();
const canvas = muze
.canvas()
.rows(["Horsepower"])
.columns(["Cylinders"])
.data(data)
.mount("#chart");
Create an UI element
Now, we will create a dropdown using html:
<select name="dropdown" id="dropdown">
<option value="">Select a Cylinder</option>
<option value="8">8</option>
<option value="4">4</option>
<option value="6">6</option>
<option value="5">5</option>
<option value="3">3</option>
</select>
Then we will attach an event listener on it which will be triggered whenever the dropdown value changes:
const dropdown = document.getElementById("dropdown");
dropdown.onchange = () => {
const val = document.getElementById("dropdown").value;
};
Dispatch behaviour on UI element interaction
When the user selects a Cylinder value from the dropdown, then we will dispatch a highlight behaviour on the canvas which will highlight the plots which have that Cylinder value. Essentially it creates the same type of effect that we get when we hover on the chart because the hover event is mapped to the highlight behaviour. The difference is we can do it programatically on any event.
For dispatching any behaviour we need to get the firebolt instance from canvas. Firebolt class is responsible for dispatching the interactions.
const firebolt = canvas.firebolt();
Now we will call dispatchBehaviour method.
This method takes the following arguments:
- behaviour: Name of the behavioural action i.e highlight, select or brush
- payload: This contains the criteria and other information required to dispatch the behaviour. criteria object takes a dimensions array or a range object. For dimensions, we need to pass the name of the dimension and the values of the dimensions in an array.
if (val) {
firebolt.dispatchBehaviour("highlight", {
criteria: {
dimensions: [["Cylinders"], [val]],
},
});
} else {
firebolt.dispatchBehaviour("highlight", {
criteria: null,
});
}
When the user selects any null value then we reset the highlight behaviour by passing criteria as null.
Example
const { muze, getDataFromSearchQuery } = viz;
const data = getDataFromSearchQuery();
const canvas = muze
.canvas()
.rows(["Horsepower"])
.columns(["Cylinders"])
.data(data)
.width(700)
.height(700)
.mount("#chart");
const dropdown = document.getElementById("dropdown");
dropdown.onchange = () => {
const val = document.getElementById("dropdown").value;
if (val) {
canvas.firebolt().dispatchBehaviour("highlight", {
criteria: {
dimensions: [["Cylinders"], [val]],
},
});
} else {
canvas.firebolt().dispatchBehaviour("highlight", {
criteria: null,
});
}
};