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
event.target
and fallback toevent.srcElement
elem = event.target || event.srcElement;
Keyboard events
- To know which key was pressed, use
event.keyCode
and fall back toevent.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 useonkeyup
. - 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
andevent.ctrlKey
respectively are true. ThekeyCode
s for these are less reliable on Mac.
Note: keypress
event always returns 0 in Firefox.
Reference: http://www.quirksmode.org/js/keys.html
Callbacks and this
- Value of
this
pointer is lost in callback functions. So,function outerFunction() { function print() { console.log('viky'); } setInterval(this.print, 1000); }
won’t work. Because inside
setInterval
, the value ofthis
is lost. You can overcome this by copyingthis
to something else, saythat
.function outerFunction(that) { var that = this; function print() { console.log('viky'); } setInterval(that.print, 1000); }
This can make your code messy. I would suggest you use Underscore.js
bind
andbindAll
methods to bindthis
to functions.
Miscellaneous
- Accessing characters in a string using normal way of indexing arrays, as in
str[i]
works fine in all browsers except IE. So, always use
str.charAt(i)
split
function using regular expressions as below doesn’t work in IE.var str = 'somestring'; str.split(/[sr]/);
- 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.