Skip navigation

Monthly Archives: February 2010


You can comment in two ways in JavaScript code.

1) First one is to comment single line. For that we use two front slashes like //. Then the entire line will be considered as comment

Example

// This is a comment in JavaScript code

2) Second one is to comment multiple lines. For that we use start with /* and end with */
Example

/* This is the multi line
comment is JavaScript code */

So, where is the shock???

When you are using regular expression, be careful because you may encounter error.

/*
var reg = /a*/.match(str);
*/

So even when using comments, you should be careful…

Hope this will help…

Advertisements

How to bind multiple functions to an event?

You can bind two functions to an event. Let us consider the code below

window.onload = firstFn;
window.onload = secondFn;
function firstFn(){var myFirstFunction;}
function secondFn(){var mySecondFunction;}

Shock: You can’t bind two functions to window.onload event like above. The second function overrides the first one. Now onload only binded with secondFn function.

How to do it correctly? Here it is

fol = function(){var myFirstFunction;};
sol = function(){var mySecondFunction;};
col = function(){fol(); sol();};
window.onload = col;

Define a new function and call two function inside the definition of newly created function. Assign new function to onload event. If you don’t know already any function is binded with onload, here comes the solution

Basically you need to chain like this

var sol = function(){var mySecondFunction;};
if(window.onload){
    var fol = window.onload;
    var col = function(){fol();sol();};
    window.onload = col;
} else {
    window.onload = sol;
}

If you are working in a team environment, you might not know wheather other developers already binded any functions on a particular event. So this technique may be useful.

Here comes most compact version (thanks to ppk)

var old = (window.onload) ? window.onload : function () {};
window.onload = function () {old(); sol()};

First you define a variable old. If the window currently has an onload event handler, put this event handler in old, if it hasn’t, put an empty function in old. Second line isobvious.

Hope this helps you people. 🙂