Change Equation of a Graph

From JSXGraph Wiki

This example shows how you can change the equation of a graph without creating the whole construction again. Dependent elements are updated automatically.

How to Create this Construction


Adding a text input field somewhere on the page together with a button

<input type="text" id="eingabe" value="Math.sin(x)*Math.cos(x)">
<input type="button" value="set" onClick="doIt()">

JavaScript Part

Setting up the board

board = JXG.JSXGraph.initBoard('jxgbox', {boundingbox: [-6, 12, 8, -6], axis: true});

Create a JavaScript Function f(x) From the Text Field

eval("function f(x){ return "+document.getElementById("eingabe").value+";}");

Use f(x) for defining the Graph

graph = board.create('functiongraph', [function(x){ return f(x); },-10, 10]);

The slope triangle

//glider on the curve
p1 = board.create('glider', [0,0,graph], {style:6, name:'P'});
//define the derivative of f
g = JXG.Math.Numerics.D(f);
//a point on the tangent
//                                 variable x coordinate           variable y coordinate depending on the derivative of f at point p1.X()
p2 = board.create('point', [function() { return p1.X()+1;}, function() {return p1.Y()+JXG.Math.Numerics.D(graph.Y)(p1.X());}], {style:1, name:''});
//the tangent 
l1 = board.create('line', [p1,p2],{}); 
//a third point fpr the slope triangle
p3 = board.create('point', [function() { return p2.X();}, function() {return p1.Y();}],{style:1, name:''});
//the slope triangle
pol = board.create('polygon', [p1,p2,p3], {});
//a text for displaying slope's value
//                               variable x coordinate          variable y coordinate                        variable value
t = board.create('text', [function(){return p1.X()+1.1;},function(){return p1.Y()+(p2.Y()-p3.Y())/2;},function(){ return "m="+(p2.Y()-p3.Y()).toFixed(2);}],{color:ff0000});

Change the plotted function

function doIt(){
  //redefine function f according to the current text field value
  eval("function f(x){ return "+document.getElementById("eingabe").value+";}");
  //change the Y attribute of the graph to the new function 
  graph.Y = function(x){ return f(x); };
  //update the graph
  //update the whole board


The doIt() function is only responsible for updating the graph. All other dependend objects are self-updating, especially the object p2 which depends on the derivative of function f. This is all done by anonymous functions of JavaScript.