Archive for the ‘javascript’ Category

JavaScript loop performance

Thursday, April 17th, 2008

Robert Nyman, the original author of the perfect little JS library, DOMAssistant, has done a little loop speed test and has come to a very useful conclusion that saves a lot of processing time. Next time you do a for loop through an array, start by saving the array.length into a variable, and use that:

for (var i=0, il=divs.length; i // Magic
}

Why is this faster? Well, if we don’t use the variable il, and do the loop like (i=0; i

onkeypress: IE and JavaScript

Tuesday, April 1st, 2008

I have been fiddling with a script today for quite some time, trying to go around Microsoft’s buggy implementation of the DOM in their browser. Yes, Internet Explorer not only lacks proper CSS rendering capabilities, but has problems on the scripting side as well.
My problem was that I needed to listen for a key press, so that I know when [space] or [enter] is pressed by the user. Luckily for me, Firefox, Opera and Safari know about event.which. IE6 doesn’t. IE7 (still) doesn’t. Microsoft thought that using window.event.keyCode would be so much more chic. I found out about this from the w3schools.com website. As I soon found out, their code was flawed. Really, there’s just one tiny bug, triggered by the lovely IE7. We should not use e.keyCode, but window.event.keyCode.


function onkeypress(e){
if(window.event) // for IE
var keynum = window.event.keyCode;
else if(e.which) // for all the abnormal, stupid and useless other browsers
var keynum = e.which;
}

Eat that irony, Microsoft is not changing. This worked for me though, for onkeypress, onkeyup and onkeydown. Does it work for you?

Careful when changing “style.display” with JS

Tuesday, April 1st, 2008

A client of mine pointed me to a small bug in Internet Explorer that kept his site from working. I was hiding/showing some tables, based on what radio button the user selects. Pretty simple, but since they were tables, I thought I should set style.display to a value like “table” for when I needed to render the table (I used “none” for hiding). Surprised that this does not work on IE? I know I was.
The error both IE6 and IE7 displayed was “Could not get the display property. Invalid argument.” Which is weird, since I’m not getting, I’m only setting.

It appears that IE does not attribute values like “table”, “table-row” and the like to the style.display property. To solve this, you should set it like:

style.display = ”;

That will revert the element to its initial display state, and in consequence any style.dispay you previously set in the script will be overwritten.
Now, this is a great tip and one worth spreading. Here’s another one:

Always hide elements using JavaScript, not CSS.

Instead of defining a css rule to set the element hidden, leave it as is and hide it in the beginning of your script. In this way, when JS is disabled, your elements will still be there.