Monthly Archives: October 2011

Make your Javascript work perfect anywhere

For the past few weeks, I had a chance to work closely with Javascript and to understand it better;). I hope this post on my discoveries will help someone. Note this post is only about the cross-browser issues in javascript those I came across; I hope to write another post on general javascript tips.

One very basic thing you should always keep in mind while javascripting is that,

The environment on which your code will run is not in your hands.

Yes, the javascript engine which is going to compile your code may be a Spider Monkey, a TraceMonkey, a JägerMonkey, a Carakan, a SquirrelFish, a V8, a Chakra or even the sucking WSH. So you have to make sure that your code runs smart with any browser. Understanding how each of these engines work takes quite a lot of time. When you want to develop a cross-platform highly interactive web app in a short time, the following things are good to keep in mind.

Event handling

  • To know in which element the event occurred, use and fallback to event.srcElement
    elem = || event.srcElement;

Keyboard events

  • To know which key was pressed, use event.keyCode and fall back to event.which
    key = event.keyCode || event.which;
  • Use onkeydown if you want the event handler to be called continuously while the key is pressed and held. Suitable for backspaces, arrow key navigation, etc. Otherwise use onkeyup.
  • Never rely on punctuation keys. (These keys are dependant not only on browser and operating system, but also on keyboard configuration and the official system language).
  • To detect Alt, Shift and Ctrl keys, check if event.altKey, event.shiftKey and event.ctrlKey respectively are true. The keyCodes for these are less reliable on Mac.

Note: keypress event always returns 0 in Firefox.


Callbacks and this

  • Value of this pointer is lost in callback functions. So,
    function outerFunction() {
      function print() {
      setInterval(this.print, 1000);

    won’t work. Because inside setInterval, the value of this is lost. You can overcome this by copying this to something else, say that.

    function outerFunction(that) {
      var that = this;
      function print() {
      setInterval(that.print, 1000);

    This can make your code messy. I would suggest you use Underscore.js bind and bindAll methods to bind this to functions.


  • Accessing characters in a string using normal way of indexing arrays, as in

    works fine in all browsers except IE. So, always use

  • split function using regular expressions as below doesn’t work in IE.
    var str = 'somestring';
  • Comma at the end of an array or any object as in
    var position = { x: 5, y: 10, };

    works fine in all browsers but throws error in IE.