'apexcharts add click event to label
I have an line-bar-area apexchart.
That looks like this:
I succeeded to add an onclick event to the datapoints.
But I would like to add an onclick event to the labels (like 01, 02, 03, 04, 05)
Does anyone knows how to do that?
The code I use for the datapoints is this:
var options = {
chart: {
height: 400,
type: 'line',
stacked: false,
events: {
dataPointSelection: (event, chartContext, config) => {
var selecteddate = pad(config.dataPointIndex + 1, 2);
console.log(selecteddate);
}
}
}
This works but how can I add events to the labels?
Or is this not possible?
Solution 1:[1]
I managed to do it by adding an event listener to my page.
It may be not the label, but the tooltip is also great.
$(".apexcharts-xaxistooltip").click(function(){
var selecteddate = $(this).text();
// do something
});
After that I also overwrite the css of the tooltip.
.tooltip-inner {
background-color: #00acd6 !important;
/*!important is not necessary if you place custom.css at the end of your css calls. For the purpose of this demo, it seems to be required in SO snippet*/
color: #fff;
}
.apexcharts-xaxistooltip{
opacity: 1;
pointer-events: all;
}
.apexcharts-xaxistooltip:hover{
background: #46A7B3;
color: white;
cursor: pointer;
}
This gives me the nice hover effect and clickable cursor.
In this way the tooltips are clickable and won't fade out when out of hover.
Solution 2:[2]
I was having the same problem for a while, if anyone is experiencing a case scenario where onClick is needed on the labels here's how I solved it:
componentDidMount () {
//get the DOM elements of the labels , classes may vary so check in dev tools.
const labels = document.querySelectorAll('.apexcharts-text.apexcharts-yaxis-label')
// you'll get NodeList so iterate & add click event listeners
labels.forEach(item => {
item.addEventListener('click', event => {
// do whatever onClick
console.log(event.target)
})
})
}
Solution 3:[3]
Today (6 may 2022), there is a specific event for this, e.g.
legendClick: function(chartContext, seriesIndex, config) {
// get the id of the chart-element to get the specific chart (I have multiple charts on a page)
console.log('chartConfigId', chartContext.el.id.split("-")[2]);
console.log('seriesIndex', seriesIndex);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jbadminton |
Solution 2 | HiLuLiT |
Solution 3 | Lambert |