IE7 cancel onbeforeunload

I was using the onbeforeunload event to confirm the user wants to leave the page with changes, something similar to when you create a new mail in Gmail. Supposedly, setting the event.returnValue to a String will activate a browser prompt when you leave the page. Setting it null makes it not prompt, after I decided that there were no changes made.

But that only worked in FF2. IE showed a “null” as the message. No matter what I set for the event.returnValue in IE, it prompted. I even tried setting the returnValue to false, and event.cancelBubble = true, but nothing worked.

Finally by trial and error, the only way to make IE not prompt is to NOT set it at all. Don’t call event.returnValue = something. This works for FF2 too, so I’m done.

Loop antipattern

Consider the following snippet:

boolean left = true;
int m = 0;
while (m < 2400) {
  System.out.println(left ? "left" : "right");
  left = !left;

could be improved as:

for (int m=0;m<2400;m++) {
  System.out.println(m%2==0 ? "left" : "right");

The antipattern to be recognized here are:

  1. The number of iterations was known at compile-time. This is a hint to use for loops. Whiles are used when the number of iterations are unknown. Although it is possible to write it as a while loop, a for loop makes your intention concise, and less error-prone (such as forgetting to increment).
  2. Modulus can be used for "cycles". In this case it was a 2-item cycle, therefore a ternary operator was used. A cycle with more items can also be used by using an array to reference the items, then use array[m%array.length] to index the cycle item.

Disclaimer: Although the code was actually written (not by me), it is not meant to shame or blame. It is to be taken as a lesson for sharing and improvement.