javascript void(0) for HTML link

May 27, 2012

To create a HTML link which does nothing when user clicks it,  use  like below


<A HREF="javascript:void(0)">Click here to do nothing</A>

When the user clicks the link, void(0) evaluates to undefined, which has no effect in JavaScript.

References –

https://developer.mozilla.org/en/JavaScript/Guide/Expressions_and_Operators#void

Here is a stackoverflow.com link, which answers why  void(0)  is better than using #  for this requirement

http://stackoverflow.com/questions/134845/href-for-javascript-links-or-javascriptvoid0


Referencing variables in setTimeout function – Javascript Closures

May 26, 2012

Requirement

– Reference For loop variable i  in setTimeout function

Wrong way

for(var i = 1 ; i <= 10; i++) {
console.log('i in for :: ' + i);
setTimeout(function() {
console.log(' i in timeout :: ' + i);
}, 2000);
}

Ouput

i in for :: 1
i in for :: 2
i in for :: 3
i in for :: 4
i in for :: 5
i in for :: 6
i in for :: 7
i in for :: 8
i in for :: 9
i in for :: 10
i in timeout :: 11
i in timeout :: 11
i in timeout :: 11
i in timeout :: 11
i in timeout :: 11
i in timeout :: 11
i in timeout :: 11
i in timeout :: 11
i in timeout :: 11
i in timeout :: 11

Right way using Closures

for(var i = 1 ; i <= 10; i++) {
console.log('i in for :: ' + i);
setTimeout(function(j) {
return function() {
console.log(' j in timeout :: ' + j);
}
}(i), 2000);
}

Ouput

i in for :: 1
i in for :: 2
i in for :: 3
i in for :: 4
i in for :: 5
i in for :: 6
i in for :: 7
i in for :: 8
i in for :: 9
i in for :: 10
j in timeout :: 1
j in timeout :: 2
j in timeout :: 3
j in timeout :: 4
j in timeout :: 5
j in timeout :: 6
j in timeout :: 7
j in timeout :: 8
j in timeout :: 9
j in timeout :: 10

References  –
http://jibbering.com/faq/notes/closures/

https://developer.mozilla.org/en/JavaScript/Guide/Closures