✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
🏦 Standard & Poor's chooses Dash Enterprise for ESG analysis. Learn why, sign up for the June 23 Webinar here!

Get selected rangeselector button event

I have a streaming data plot which uses a Plotly.extendTraces call. This requires setting a dynamic range in a Plotly.update call:

{'xaxis.range': getDynamicRange(timeScale)}

where the range is determined by a variable timeScale:

var timeScale = '1h';
getDynamicRange = function (scale) {
  var now = new Date(),
	past = new Date(now);
  switch (scale) {
	case '1m':
	  past.setMinutes(now.getMinutes() - 1);
	  break;
	case '1h':
	  past.setHours(now.getHours() - 1);
	  break;
	case '6h':
	  past.setHours(now.getHours() - 6);
	  break;
	case '12h':
	  past.setHours(now.getHours() - 12);
	  break;
	case '24h':
	  past.setHours(now.getHours() - 24);
	  break;
	case 'all':
	  break;
	default:
	  break;
  }
  return [past, now];
}

I have noticed that when using the rangeselector the range must be dynamically changed as well. The arguments of the switch-case statement correspond to the labels in the rangeselector buttons. So I would like to use a plotly event to determine which rangeselector button was clicked, get its label and pass it to the dynamic range function.
I have looked at the arguments passed by the plotly_relayout event and it doesn’t seem to give me which rangeselector was clicked. The plotly_clicked does not trigger at all when a rangeselector button is clicked.

How can i get the rangeselector button label when clicked?

It turned out to be quite simple…
i solved this problem by attaching a click event to the buttons:

$('.rangeselector').children('.button').click(function (event) {
  timeScale = this.textContent;
});

This gets the label from the clicked rangeselector button and assigns it to global variable timeScale.
On the next call to getDynamicRange() by the Plotly.update function it uses the new timeScale.

Hi nlooije,

I’m trying to implement something like your solution, but not being so expert, could you please be specific about how to set this solution? I mean, the basics. Do you have to create a .js file into assets folder and write this click event snippet?

Thanks