PlotlyJS Event Handlers with Flask


I am trying to get selected event data back from a graph in a Flask app. I am looking at the example here: which seems fine but I can’t get it to work in Flask.

In the Flask JS, I have a function that executes when the user clicks a Submit button, that fills the graph div. I want to be able to make calculations based on area selections. When I put a function like the one in the example in the .js file, it never executes because graphDiv isn’t defined until the user clicks Submit in the first place. (disclaimer: I don’t really know javascript).

Then I tried including a JS snippet in the HTML file, that (as far as I know) ought to activate upon a plotly_selected event. It looks like this:

<script type="text/javascript">
    var graphDiv = document.getElementById('plot-container');
    graphDiv.on('plotly_selected', function(eventData) {

Now graphDiv should be properly defined, but when I do lasso or rectangle selection on the graph, nothing is logged to the console, so I assume a ‘plotly_selected’ event has not been triggered.

Is there a way to check if an event has been triggered? But more importantly - how can one go about getting selected event data from a Plotly graph in a Flask app? A working example would be wonderful!