Adding events to elements on run-time (JavaScript)

I encounter many situations where I have to add events to element in JavaScript runtime, with each element  having similar event handlers with variables, say keys on a numpad, where each key has to register a different digit value. How would you do that?

I used to handle these situations by adding attributes to HTML and accessing the attributes from the event ‘target’ inside the event handler function. There is a problem with that technique.

  1. The event handler has to fetch the attribute and do string processing to flesh out the original parameters.
  2. Manipulation of HTML attributes adds to code latency and code complexity.
  3. String processing to flesh out the parameters adds complexity (e.g regular expression) even to a simplest event handler.

I have two solutions to overcome this particular problem…

Solution 1 (Using JavaScript’s super generous object model)

Anything in JavaScript is an object, extensible object. So you can actually add a property to the DOM object itself in order to access that in event handler run-time.

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

  //Generating elements in run-time
  for(var i = 0; i < 12; i += 1){
    var p = document.createElement('p'); //Creating element p
    p.innerHTML = 'Click me! ' + i;
    p.i = i;//Attaching a particular variable with value to the DOM object

    p.addEventListener('click', function(e){
      alert('You clicked ' + this.i); //Getting that particular value inside the event handler

You can see a working version here at

In this example, you can see that I have attached ‘i’ to the object ‘p’ which I can use as a fixed parameter for the event handler. This solution though effective can pose a few problems.

  1. Name conflicts. You can use variable naming conventions and namespaces to counter this problem.
  2. It’s very effective because most of the code is being handled inside the JavaScript engine. Less code latency.
  3. When working with many coders, you might not want to fiddle with the object itself.
  4. The event handler can access all the object properties of the parent by using ‘this’. No need to use “”.

Solution 2 (Creating functions with closures)

You can create unique individual functions while defining the event handlers. JavaScript has a very special property called Closure. Once a object has been created, you cannot change the enclosed variables. This also can be used to create dynamic event handlers on run-time.

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

  //Generating elements in run-time
  for(var i = 0; i < 12; i += 1){
    var p = document.createElement('p'); //Creating element
    p.innerHTML = 'Click me! ' + i;

    p.addEventListener('click', new function(e){
      var x = i; //Setting the variable inside enclosure
      return function(){ //The actual event handler
        alert('You clicked ' + x);

Try out the code at

In this example, I have returned the event handler function from an object initialization. Here I have used closure. Each time a new object is initialized, it returns a function as the event handler. And thanks to closure, the ‘x’ inside the parent object stay intact. Points to be noted,

  1. Creating functions inside function is discouraged by JSLint, but I believe it’s quite good if used in moderation.
  2. Closure can be a very useful feature if used properly. But one must be careful about naming and scopes when writing complex event handlers.
  3. This method compare to the previous one is a little more memory hogging, but it doesn’t interfere with the original DOM objects.

In both these cases, each time a event handler is initialized a new function or object is created, which is quite a waste. On my next post I will talk about how to efficiently create objects are deal with events dynamically.

You may try fiddling with the codes on CODEPEN.. JavaScript is an amazing creature you can actually enjoy learning about.

Nodal Identity

I was really inspired by MIT Media Lab Identity few years back. I liked the idea. Few days ago this Media Lab Identity thing sprung up on me, and I thought of a visual presentation scheme which would be aesthetically pleasing and also will be able to deliver a neat visual representation of each node in a tree like data set.

After thinking over a sleepless night, I sought this scheme out.

Let me explain.

In a tree-like data structure each node has a set of ancestors, going up to the top level (except for the top level nodes). In this version of the representation scheme, I scattered each node randomly over a grid and decided to render a single unique image for a single node, while each image containing not only the point of the node itself, but of it’s ancestors as well, straight up to the top level (except, again the top level nodes).

A dull image of a top level node,

While the test data set contained a 5 level tree, a third level node looks like this, depicting not only the third level (green) node, but also it’s ancestors (yellow and red).

You can also visualize relationships between nodes, such as,

In these two nodal images, you can see both these nodes belong to the same parent. (red, yellow, and green square is in the same positions while the blue changed). On the other hand,

These two have a great-grandfather type relationship.

The current version of the generator accepts the whole data-set at once in a tabular form and churns out the images. Written in Python & Processing.

Feel free to hack into it at Also contains test data generator.

Movement tracking – First version

In the beginning I tried to generalize motion tracking system. Previously I tried to detect a colored object and rotate the camera accordingly. The fundamental concept of operation is to detect movement by detecting changes between two consecutive frames. The camera rotates according to the movement and tries to keep the moving object in frame.


It uses OpenCV with Python bindings to run the computer vision routines. The whole computer vision subsystem contains image processing followed by contour detection. The camera rotation platform uses a stepper motor that is controlled by a Atmel ATmega8L micro-controller which is connected to the computer with a Bluetooth Serial modem.

The custom PCB that contains the ATmega8L and the Motor driver that driver the motor…

Camera mounted on the rotor

There is a lot of room for improvement. I will continue to work on this.

This was my B. Tech Final Year Project.

All codes are on including the AVR Studio Project files required to compile and program the micro-controller that is responsible for interfacing the camera rotation with the computer. The complete report is also here.

Project Log Entry 2

For my final year project, I initially planned to use Kalman filtering for motion detection, but as I couldn’t make the Kalman Filtering work on time, I settled with a color based tracking system. Simply converting the whole camera image to HSV color-space and setting a rang for a particular color, I tracked the colored blobs. Next I will be using Kalman filtering.

The computer vision library used was OpenCV, running with Python bindings. The system is communicating with the computer via Bluetooth and there is a webcam fitted on the rotation mechanism that I built from old printer parts.

Here is a video of it in action,

Delta modulation experiment

When I first learned about Delta modulation I realized it has a lot of potential for low-digital-bandwidth voice communication. With a single bit data-frame audio communication will be quite easy. This is one among my old experiments. I simulated a delta-modulation-demodulation system with various quantization steps and figured out it’s frequency response.

I did set the sampling rate to 4 times (as suggested by a communication book) the Nyquist Rate. That is 2 x 20kHz x 4.

The surface plot is the correlation co-efficient at those particular quantization steps and input sinusoidal frequency.

Here is the response,

I found out that it’s quite good for voice communication, upto 8kHz it will perform pretty well. The red region suggests good communication will occur upto 8kHz at small quantization steps. The the quality of the communication will gradually fall.

Next I will put a audio file through delta modulation.

The MATLAB code with the Delta modulation simulation model (.rar file) is here at

Moving average filter experiment

This is one of my old experiments I did when I started to learn about digital signal processing. I was intrigued by the simplicity of a moving average filter and did an experiment on frequency response of a moving average filter vs. number of averaging elements.

I found out that is has somewhat a cosine frequency response, and does have excellent low pass characteristics, although have some little curves on higher frequencies.

Here is the response vs. number of averaging elements. I plotted the surface with Number of Averaging Elements/Sampling rate. That way it’s easier to realize the duration of averaging.

Here is the MATLAB program that generates this surface plot,

I also put a sound files through my moving average filter. I don’t exactly remember the number-of-averaging-elements I used but the low pass characters was very impressive. You can use Windows Media Player Bar spectrum analyzer visualization to visualize that, or you can use a good pair of headphones/ speakers to see the difference.

Here is the real sound file and

Here is the filtered sound file

JavaScript Speed Test

I started out to test out the speeds of JavaScript engines in the browsers. I was keen to experiment on the Chrome’s high performance V8 JavaScript engine. I designed this very rudimentary experiment to compare two JS engines (the one in Firefox and the one in Chrome). IE didn’t really support the DOM and the experiment didn’t work out, and I was not keen to make the whole thing work on IE. I am not an IE person.

The experiment is a page that has a math intensive JavaScript program that will compare the starting and ending time in machine timecode and publish the difference on page. The JS script is designed to do Sine, Cosine operations and store the values and then print them on the page. The page also has some CSS elements.

The page can be downloaded.

The results I got on my Core i3 laptop with 3 Gigs of RAM running Windows 7 Home Basic…

On Firefox (click to enlarge),

On Google Chrome,

And on IE where the script didn’t work,

The V8 engine that powers node.js I thought would be a lot faster. Google claims the power of V8 lies on it’s garbage collection system. I didn’t look into garbage collection though. But the speed, as you can see is slower than Firefox.

I didn’t test it on Safari, Opera etc. If anyone compares them, please let me.