M Waz
M Waz

Reputation: 775

Running external javascript file that edits graph in html file

I have a button in my html page that I want to run an external javascript file after being clicked.

<input type="button" id="btn" value="Show Graph" onclick=src="graph.js">

The javascript file in question is:

$(document).ready(function(){
  $("#btn").click(function(){
    $("#tester").load("", function(){
  TESTER = document.getElementById("tester");

  Plotly.plot(TESTER,[{
    x: [1,2,3,4,5,6,7,8,9,10],
    y: [1,4,9,16,25,36,49,64,81,100]}],
    {margin: {t:0}});
    });
  });
});

The goal of this file is to edit and draw a graph in:

<div id ="tester" style="width:600px;height250px;">
</div>

What do I have to do so that my javascript file is able to edit the element on my html page?

Upvotes: 0

Views: 308

Answers (1)

JJFlash42
JJFlash42

Reputation: 131

It looks like you want to use plotly.js. First you have to include the library in the head of your HTML document

<head>
...
  <script type="text/javascript" src="https://cdn.plot.ly/plotly-latest.min.js"></script>
...
</head>

Then you can add the function you posted, but you should modify it a bit

<head>
...
  <script type="text/javascript" src="https://cdn.plot.ly/plotly-latest.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function(){
      $("#btn").click(function(){
        Plotly.plot(document.getElementById("tester"),
         [{ x: [1,2,3,4,5,6,7,8,9,10],
            y: [1,4,9,16,25,36,49,64,81,100]}],
         {margin: {t:0}});
      });
    });
  </script>
...
</head>

This will add the plot function call to the onClick event of the button with the id btn. The HTML declaration of the button does not need the onclick event set anymore so it should look like this

<input type="button" id="btn" value="Show Graph">

Note that your javascript makes use of jQuery, so you need to include it in the header as well.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

You can also put the jQuery and Plotly libraries on your webserver and load them from there as opposed to the externally hosted examples here. Then you would use the relative path to the library on the webserver, e.g.

<script src="js/jquery.min.js"></script>

If you want the function in a separate javascript file, put the call to the function into the button

<input type="button" value="plot" onclick="drawPlot()">

then write the function into a textfile i.e. myplot.js and then include it in the header

<script type="text/javascript" src="myplot.js"></script>

You have to modify your function like this

function drawPlot () {
  Plotly.plot(document.getElementById("tester"),
     [{ x: [1,2,3,4,5,6,7,8,9,10],
        y: [1,4,9,16,25,36,49,64,81,100]}],
     {margin: {t:0}});
  });
}

Upvotes: 2

Related Questions