javascriptreactjsanychartanychart-8.2

How to catch the range picker button click events and apply a simple transformation to the data?


In this Range Selection section and examples it shows how to add range picker buttons (10D, 1M, 3M, YTD, 1Y, 2Y, 5Y, and MAX) to the stock plot. See the example from that documentation in the AnyChart Playground STOCK_Range_Selection_01.

In my use-case I am comparing prices for multiple funds and I would like to catch the event when any of the ranges is clicked e.g. YtD, then transform the prices for all active series and re-scale them to start from 1. so that the different prices are comparable performance-wise starting at that new X origin. Basically I would have prices1, prices2 and prices3 and divide each by its respective starting price so they become a comparable wealth index starting on that new X origin and with price value of 1.0 e.g.

price1.loc[YtD, :] = price1.loc[YtD, :] / price1.loc[YtD] 
// note that price1.loc[YtD] == 1.0

How can I do that using AnyChart?


Solution

  • To achieve the desired behavior, you could use the getElement() method as shown below.

    anychart.onDocumentReady(function () {
      var dataTable = anychart.data.table();
      dataTable.addData(get_dji_daily_short_data());
    
      var mapping = dataTable.mapAs({value: 1});
    
      var chart = anychart.stock();
    
      var plot = chart.plot();
      plot.line(mapping);
    
      var rangeSelector = anychart.ui.rangeSelector();
    
      chart.title('Get element');
      chart.container('container');
      chart.draw();
    
      rangeSelector.render(chart);
    
      // Get element.
      var button = rangeSelector.getElement();
      
      // use a listener to trigger your code
      button.addEventListener("click", (event) => {
        alert(event.target.innerHTML);
      });
    });
    

    You could also take a look at the sample we've created on our playground.