Friday, November 5th, 2010

Turning off the lights with jQuery

A recent website I created for EME Solutions Ltd gave me the opportunity to be creative with jQuery.

Being a website for an Electrical contractors I had the idea to create a light switch in the background of the website which when clicked turns off the lights.. You can visit the site or check the video below to see the effect.

Can’t see the video? download it in mp4, webm or ogv format.

Here’s how the effect is achieved.

First I created the light switch (off and on states) and the animated gif for the eyes:

Next it’s in the code, we need to do several things;

  1. Add the light switch to the page background, add a <div> to work as the black overlay for the page and the html to contain our eyes and text which will appear on top of the overlay. Hide the overlay and its content.
  2. When a user clicks on the light switch, change the image source to the image ‘on‘ state, fade-in the overlay and its contents.
  3. After a short delay fade the overlay out and reapply the light switch ‘off‘ state.

Style and position the elements using CSS:

/* position the light switch - this is absolute to the body */
#lightswitch {position:absolute; top:180px; left:50px;}

/* show a pointer on hover to indicate the switch is clickable */
#lightswitch:hover {cursor:pointer;}

/* position our overlay over the top of other elements and use a transparent png for the background - hide by default */
#black {background:url(images/blackBg.png); position:absolute; top:0; right:0; left:0; height:100%; z-index:999; display:none;}

/* position content to the center of the page */
#eyesCall {background:url(images/eyes.gif) no-repeat center top; width:400px; height:100px; position:absolute; top:50%; left:50%; margin:-50px 0 0 -200px; color:#fff; font-weight:bold;}

#eyesCall p {position:absolute; bottom:0; left:0; width:400px; text-align:center; font-size:1.1em;}

Add the elements and functionality using jQuery:

<script type="text/javascript">
//when the document is ready

   //add the light switch and overlay html to the page before the container element
   $('#container').before('<img src="" id="lightswitch" /><div id="black"><div id="eyesCall"><p>Call EME to turn on the lights - 07889 758441</p></div></div>');

   //when the light switch is clicked

      //change the src attribute of the image to the 'on' state
      $(this).attr('src', '');

      //fade in our overlay containing the html

         //after a delay of 2.5 seconds fade the container back out
            //change the light switch image src back to the off state
            $('#lightswitch').attr('src', '');

Ta Da!

Leave a Reply