Javascript Window Shake

This evening I came accross the window.moveBy() JavaScript function and thought it would be cool to shake the browser window when a user fails to log in. It turns out that I was not the only one thinking this, but none of the examples worked for me. Some had no proper delays, others only worked from the page header, and some were plain unreadable.

I'm no Javascript guru, but I hacked this together which is working pretty nicely. It is in fact almost undistinguishable from the Apple login window shake at a login failure:

<script type="text/javascript">
if (window.moveBy) {
	delay = 70;
	shakes = 3;
	window.moveBy(-10, 0);
	for (j = shakes; j > 0; j--) {
		setTimeout( "window.moveBy(20, 0)", j*delay );
		setTimeout( "window.moveBy(-20, 0)", 
					j*delay+(delay/2));
	}
	setTimeout( "window.moveBy(10, 0)", (shakes+1)*delay );
}
</script>

In my case, I surrounded this code with a Tapestry @Conditional and made it into a reusable Tapestry component so that I can make any window shake as soon as it contains an error.

The code will work anywhere on your page, but I advise you to put it at the bottom of the HTML. This will make sure that the content is shown in the browser before you shake it.

It's visually much stronger than just adding an errortext to the page. If people log in a couple of times a day, they don't even notice extra text on the screen. This will "shake" them awake :-)

Have fun!