xxxxxxxxxx
95
<html>
<head>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<style>
body {
background-color: #fff;
color: #000;
}
body.dark-mode {
background-color: #000;
color: #fff;
}
</style>
</head>
<body>
<div id="plot"></div>
<form>
<label for="equation">Enter an equation:</label>
<input type="text" id="equation" name="equation" placeholder="e.g. 2*x^2 + 3*x + 1">
<br>
<button type="submit">Plot</button>
</form>
<label for="dark-mode-switch">Dark mode:</label>
<input type="checkbox" id="dark-mode-switch">
<script>
var trace = {
x: [], // x-axis values
y: [], // y-axis values
type: 'scatter',
mode: 'lines',
line: {color: 'red', width: 2}
};
var layout = {
xaxis: {title: 'x-axis'},
yaxis: {title: 'y-axis'},
};
// Parse the equation and return a function that computes y for a given x
function parseEquation(eq) {
var match = eq.match(/^ *(-?\d*\.?\d*)? *\*? *x\^2 *([+-] *\d*\.?\d*)? *\*? *x *([+-] *\d*\.?\d*)? *$/);
if (match) {
var a = match[1] ? parseFloat(match[1]) : 0;
var b = match[2] ? parseFloat(match[2].replace(/\s/g, '')) : 0;
var c = match[3] ? parseFloat(match[3].replace(/\s/g, '')) : 0;
return function(x) { return a * x * x + b * x + c; };
} else {
return null;
}
}
// Plot the initial graph
for (var i = -10; i <= 10; i++) {
trace.x.push(i);
trace.y.push(i);
}
var data = [trace];
Plotly.newPlot('plot', data, layout);
// Handle form submit event
var form = document.querySelector('form');
form.addEventListener('submit', function(event) {
event.preventDefault();
var equation = document.getElementById('equation').value;
var f = parseEquation(equation);
if (f) {
for (var i = 0; i < trace.x.length; i++) {
trace.y[i] = f(trace.x[i]);
}
Plotly.redraw('plot');
} else {
alert('Invalid equation!');
}
});
// Handle dark mode switch
var darkModeSwitch = document.getElementById('dark-mode-switch');
darkModeSwitch.addEventListener('change', function(event) {
var body = document.getElementsByTagName('body')[0];
if (event.target.checked) {
body.classList.add('dark-mode');
} else {
body.classList.remove('dark-mode');
}
});
</script>
</body>
</html>