Bobylito

01 Jul 2012

Way of css, a 1k demo using CSS

Yesterday took place the second edition of DemoJS, the web-only demoparty. Being part of the organizing team but not being a demoscener myself, I was really eager to do something for the demo contest. The problem is I failed in preparing a real demo before the demoparty so let’s just say I didn’t really have any hope of starting demos this year.

Hopefully, I stood up all night (you know being part of the organization team etc) so I started hacking near by my friend @phillipeAntoine, who was tinkering on his yet to be released canvas + css demo. After a while, his experiment really started to make me think of a few way to exploit css in demos and I started this demo which is a 1k demo.

With this article, I want to share with you what I learned from this experiment. Really, do not try this at home work or small kittens will die. All of this is for the purpose of science.

Markup generation

HTML being very verbose even for small stuff, the solution is to generate it. That’s why this demo uses some javascript.

The recipe :

  1. take a sentence
  2. split it and get an array
  3. for each element generate a dom element
  4. and add it to the body

In action :

"Hi DemoJS partiers and orga! Thx 4 being awesome! CSS 
rulez! 1k is not much and yet enough. \\o/".split(" ")
.map(function(e){
  a=d.createElement("p");
  a.innerHTML=e;
  d.body.appendChild(a);
})

Delays for the win

Having a bunch of dom element is not very useful, you might argue… But there is this one little feature that makes the animation possible using CSS : DELAYS.

It gives to the css animation a pause after which it’ll start. Because the index of the word in the array gives us its position in the sentence, we can then apply a proportionnal delay. This will keep the order and we can apply the same animation with this delay to make the animation.

a.style.webkitAnimation="a 2s "+(i++)+"s 1";

The end

The demo use the animationEnd event of each animation to figure out when the last word disapear.

a.addEventListener("webkitAnimationEnd",
  function(){if(!--i)z.className='s'})

Micro page

Markup in demos should be stripped

Usually a really classic webpage would look like this :

<!DOCTYPE HTML>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title></title>
    <style><style>
  </head>
  <body></body>
  <script type="text/javascript"></sc:w
ript>
</html>

But really you can strip it, without being hurt, to something like this :

<style></style>
<body>
<script></script>

ID as variable name

In JS, you can use directly the id of a dom element like a variable. We can then do :

z.className='s'

for a dom element named with ‘z’ as its id instead of doing so :

document.getElementById("z").className='s'

Final word

The code is ugly, the demo is not very impressive but when looking back, it does contain some stuff which are quite fun to use and combine.


Comments