HOME
PDF

Javascript examples

Nasser M. Abbasi

January 16, 2020   Compiled on January 16, 2020 at 11:32am

Contents

1 XY plot using flot library
2 Click on button, box slides, using requestAnimationFrame

1 XY plot using flot library

This shows how to make a plot of a sin(x)  function. The library used is http://www.flotcharts.org/

Click on ex1.htm to see the output. The source code is

<html lang="en">
<head>
<title>
  Simple Javascript example 1
</title>
    <meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Flot Examples: Basic Options</title>
<script language="javascript" type="text/javascript" src="/scripts/flot/jquery.js"></script>
<script language="javascript" type="text/javascript" src="/scripts/flot/jquery.flot.js"></script>
<script type="text/javascript">

$(function() {
    var options = {
           series: {
              lines: { show: true, fill: false, lineWidth:1},
              points: { show: false },
              color:"rgb(0, 0, 0)"
                   }
    };
var data = [];
for (var i = -2*Math.PI; i < 2*Math.PI; i += Math.PI/10) {
data.push([i, Math.sin(i)]);
}
$.plot("#plot", [data], options);
$("#footer").prepend("Flot " + $.plot.version + " &ndash; ");
});

</script>
</head>
<body>
Example showing how to plot a sin function using flot library.

  <div id="plot" style="width:400px;height:300px"></div>

</body>
</html>

2 Click on button, box slides, using requestAnimationFrame

Click on HTML to see the output. The source code is

<!DOCTYPE html>
<html>
<!-- simple animation of box moving. Nasser M. Abbasi, January 15, 2020 -->
<body>

<p>
<button onclick="process()">Click Me</button>
</p>

<div style="width: 400px; height: 50px; position: relative; background-color:lightblue;">
    <div id ="myAnimation", style="width: 50px; height: 50px; position: absolute; background-color: red;"></div>
</div>


<p>current position: <span id="position_text"></span></p>
<p>current time: <span id="time_text"></span> (seconds) </p>


<script>
var g_is_running = false;
var g_starting_time =0;
var g_element = document.getElementById("myAnimation");
var g_max = 400-50;
var g_id;

function process()
{
  g_is_running=false;
  g_id = window.requestAnimationFrame(do_it);
}

function do_it(time_stamp)
{
  var progress     = 0;
  var new_position = 0;

  if (!g_is_running)
  {
     g_is_running = true;
     g_starting_time = time_stamp;
  }
  else
  {
     progress = time_stamp - g_starting_time;
     new_position = Math.min(progress / 20, g_max);
  }

  g_element.style.left = new_position + 'px';

  document.getElementById("position_text").innerHTML = new_position.toFixed(2);
  document.getElementById("time_text").innerHTML = ((time_stamp-g_starting_time)/1000).toFixed(2);

  if (new_position < g_max)
  {
     window.requestAnimationFrame(do_it);
  }
}

</script >
</html>