Cool light bulb animation using jQuery

Posted at February 14, 2011

You’ve found a dinosaur. This is one of my first posts about programming and the code quality is not of high standards, it is only here for archiving purposes.

Last week I’ve been messing around with jQuery and made something worth sharing. Let’s start of by showing you the demo.

As pointed out by YoYoMa, this doesn’t work in IE8

Demo of cool lightbulb animation!

As you can see there are two things happening when you turn the light on or off:

  1. You can see a red spark going through the wire towards (or away from) the lightbulb.
  2. The lightbulb will start shining with a fade effect.

Here is the code required for the animation, at the bottom I’ll explain how it works.

HTML

<div id="title">
            <img src="logoClean.png" />
            <div id="light" class="javahide">
                <img src="logoLights.png" />
           </div>
            <div id="moreLight" class="javahide">
                <img src="light.png" />
            </div>
            <div id="burn" class="javahide">
                <img src="burn.png" />
            </div>
</div>

<div id="kabel">
            <img src="cableMask.png" />
</div>

<div id="buttons">
            <p><a id="on" href="#">light ON</a></p>
            <p><a id="off" href="#">light OFF</a></p>
</div>

CSS

#light, #moreLight, #burn {
    margin-top: -275px;
}

kabel {
    position:absolute;
    top: 265px;
    left: 306px;
    margin-left: 200px;
    background-color:#c2c2c2;
    width: 500px;
    height: 50px;
    background-image:url(cable.png);
    background-repeat: no-repeat;
    background-position: 475px 0px;
}

Javascript

$(document).ready(function(){
    $(".javahide").hide();

    $('#on')
        .click(function(){
            $('#kabel').stop().animate({backgroundPosition:"(-25px 0px)"}, {duration:1000})
            $("#light").delay(1000).fadeIn(50);   
            $("#moreLight").delay(1600).fadeIn(1000);
            $("#burn").delay(2500).fadeIn(1000);
        })

    $('#off')
        .click(function(){  
            $('#kabel').stop().animate({backgroundPosition:"(475px 0px)"}, {duration:1000})
            $("#moreLight").fadeOut(10);   
            $("#light").fadeOut(50);   
            $("#burn").fadeOut(3000);   
        })
})

How does it work? Lightbulb – The shining light bulb is a combination of a few pictures on top of each other (rule 2 of the CSS makes sure of that), all the pics hidden and fade in after the button light ON is pressed.

the electric wire – Again I use multiple pictures on top of each other. I’ve made a small red ball and it’s set as background-image of the cable div. Inside the div I put a normal picture (HTML) which is white except for some transparency (the grey wire), this picture acts as a mask for the red spark.

I’ve used this jQuery background-position plugin to move the ball horizontally.