3

I'm using Plot.ly.js to add some graphs to my website. I am trying to use an external script to draw the graphs because I'll be using the same function on several different pages. At the beginning of my .aspx page, I have this:

<script src="Scripts/plotly-latest.min.js"></script>

so that I can use the Plot.ly library. In an external .js file, I have my function:

function drawLines() {
var one = {
   x: [1,2,3],
   y: [1,2,3],
   mode: 'lines+markers',
   name: 'Sample Data'
};
var data = [one];
var layout = { title: 'Sample Graph' };
Plotly.newPlot('myDiv', data, layout);

If I put that directly in my .aspx page, then it works fine, but I really want to have it be external. So, I tried adding this where I want the graph to go:

<div id="myDiv" style="width: 480px; height: 400px;">
    <script src="Scripts/LineCharts.js" type="text/javascript" ></script>  
    <script>
           drawLines()
       </script>
</div>

I also tried putting the line with src="Scripts....> in the beginning, where I do that for the Plot.ly library, as well. Anyway, neither of them worked; the graph just doesn't show up on the page (but the div element with the blank space is there). I know I should be able to use an external script quite easily, but I just don't know where/how to put it into my .aspx page so that it works. I want it to run when the page initially loads.

I realize this is very basic and probably a stupid question but I haven't worked with these things before and I could really use some help.

1 Answer 1

2

When you save your script as an external file, you no longer have access to the HTML div "myDiv". You need to explicitly get a reference to the div by adding the following to the beginning of your script:

var myDiv = document.getElementById('myDiv');

And now in your call to the Plotly.newPlot you need to pass that variable itself, not the string id, i.e.

Plotly.newPlot(myDiv, data, layout);

Also, this is more of a coding style issue, but you should call drawLines() in your external script, not in an inline script within the HTML.

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.