Added event listener on a HTML element which is retrieved by className in the render method of highcharts but that listener is getting called twice. Please check below code where click event gets called.
But somehow this handler is getting called twice. I have added below multiple solutions but it doesn’t work.
Solutions:
-
Added
e.stopPropagation()
ande.preventDefault()
but didn’t work. -
Below {once: true} solution didn’t work
label.addEventListener(‘click’, (e) => {
console.log(‘click event’);
}, {once: true}); -
Removed event listener still click function get called.
Can someone please provide solution to avoid event listener getting called twice.
2
Answers
You can pass once in method options object this will remove the eventListener when it’ll fire first time for eg
That’s because
render
event can be fired multiple times which results in multiple event listeners added. From Highcharts API:As a solution, you can use another way to add the event listeners. By using custom-events plugin or
on
method, a callback function will be fired only once.Live demo: http://jsfiddle.net/BlackLabel/uo8hc526/
Docs: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Multiple_identical_event_listeners
API Reference:
https://api.highcharts.com/highcharts/chart.events.render
https://api.highcharts.com/class-reference/Highcharts.SVGElement#on