squaredesign
we turn great ideas into excellent websites

The Squares

visitors to my site have asked me how i was able to make it load quickly with a big image/animation in the background (in the previous design)

the answer: it’s not a graphic. it’s all HTML, CSS, and Javascript.

as a designer / developer, i try to find ways of using the capabilities of the browser to provide advanced design and functionality, instead of pushing a large payload like a Flash movie down to the browser for every effect i want to create.

my inspiration came from John Resig’s port of the Processing library to processing.js. there are some really beautiful visuals in those examples, all of which are generated in the browser. while i didn’t use processing.js to create my design, i did leverage the JQuery library to do a lot of the heavy lifting for me.

for this demonstration, i won’t get into the math involved to do the random colors – that would probably fill another article by itself. instead, let’s focus on the rendering and animation.

step 1: pick a container

for this example, let’s take this <div> element:

<div id="demo"></div>

pretty boring.

step 2: fill it up

now let’s fill the <div> with smaller <div>s – a grid of them 10×6

this CSS will style the small squares that we will create:

.demo-square {
	float:left;
	width:28px;
	height:28px;
	background:#dfd;
	margin:1px;
}

here’s the javascript that creates them:

var cols = 10;
var rows = 6;
for(x=0; x<(cols * rows); x++) {
	$("<div>")
	.clone(false)
	.appendTo("#demo")
	.addClass("demo-square")
}

that gives us this:

(i styled them with a bit of margin between so you could see the separate squares)

step 3: make it go

while there are other ways to animate the squares, most of them use a lot of CPU time, and would run even when the user wasn’t watching. i got the idea to tie the animation to the mousemove() event that JQuery provides. this would insure that it wouldn’t be eating CPU cycles while the user had another tab or window focused. also, i hope it adds a bit of fun!

the CSS for the alternate square style:

.demo-square-dark {
	background:#6a6;
}

the javascript that toggles the alternate class on a random square as the mouse moves:

var demosquares = $('#demo .demo-square');
$("#demo").mousemove(function(e) {
  pick = Math.round(demosquares.length * Math.random());
  $(demosquares[pick]).toggleClass("demo-square-dark");
});

mouse over this div to see how the mousemove() event triggers that toggle

and that’s basically how the animated background of my site works. in another post, i’ll get into the details of the math that makes the different shades. until then – check out a toy i made with the background squares – you can even select the two colors that it differences between!

w
Q