I’ve been doing some work on my Christmas Countdown site to add a snowflake falling effect. I had seen other scripts on the internet but they all looked a little slow and I wanted to use CSS3. All I’ve done is create snow.js with the following code:
count = 30;
var docHeight = Math.max(Math.max(document.body.scrollHeight, document.documentElement.scrollHeight), Math.max(document.body.offsetHeight, document.documentElement.offsetHeight), Math.max(document.body.clientHeight, document.documentElement.clientHeight));
var docWidth = Math.max(Math.max(document.body.scrollWidth, document.documentElement.scrollWidth), Math.max(document.body.offsetWidth, document.documentElement.offsetWidth), Math.max(document.body.clientWidth, document.documentElement.clientWidth));
function snowflakes()
{
for (var i = 0; i < count; i++)
{
document.write("<div id=\"snowflake" + i + "\" style=\"position:absolute;z-index:1001; top:" + (-docHeight * 2 * Math.random()-50) + "px; left:" + (Math.random()*(docWidth-10)) + "px;background-color:white;width:10px;height:10px;border-radius:10px;transition:all 1s linear;-webkit-transition:all 1s linear;-o-transition:all 1s linear;-moz-transition:all 1s linear;\"> </div>");
}
setInterval("move()", 500);
}
function move()
{
for (var i = 0; i < count; i++)
{
var top = parseInt(document.getElementById("snowflake" + i).style.top.replace("px", "")) + 5 + (Math.random()*10);
if (top < docHeight - 10) document.getElementById("snowflake" + i).style.top = top + "px";
else document.getElementById("snowflake" + i).style.opacity = "0";
}
}
This effect works relatively well. To launch it add the following to the end of the body:
<script type="text/javascript" src="snow.js"></script>
<script type="text/javascript">snowflakes()</script>
On my site I’ve blocked it from coming up in IE because the transition won’t work (I’ve used PHP to do this) but it definitely works in Chrome, Firefox, Opera and Safari with Firefox offering the smoothest animation. If you find that you need more snowflakes just increase the count variable at the top of the file however you have to consider the performance of users’ computers.