skip to Main Content

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.

  1. Added link on xAxis of highchart in xAxis label formatter.
    enter image description here

  2. Added onClick handler in the render of highchart
    enter image description here

But somehow this handler is getting called twice. I have added below multiple solutions but it doesn’t work.

Solutions:

  1. Added e.stopPropagation() and e.preventDefault() but didn’t work.

  2. Below {once: true} solution didn’t work

    label.addEventListener(‘click’, (e) => {
    console.log(‘click event’);
    }, {once: true});

  3. Removed event listener still click function get called.

enter image description here

Can someone please provide solution to avoid event listener getting called twice.

2

Answers


  1. You can pass once in method options object this will remove the eventListener when it’ll fire first time for eg

    let btn = document.querySelector("button")
    btn.addEventListener('click', () => {
        console.log("Logged");
    }, { once: true });
    
    Login or Signup to reply.
  2. That’s because render event can be fired multiple times which results in multiple event listeners added. From Highcharts API:

    render

    Fires after initial load of the chart (directly after the load event),
    and after each redraw (directly after the redraw event).


    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.

      chart: {
        events: {
          render: function() {
            const xAxis = this.xAxis[0];
            const ticks = xAxis.ticks;
    
            xAxis.tickPositions.forEach(tickPos => {
              ticks[tickPos].label.on('click', () => {
                console.log('CLICK')
              });
            });
          }
        }
      }
    

    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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search