How to Create a Nifty Dynamic Shadow with jQuery

Dynamic shadow preview pictureFirst I want to welcome you to my very first article for 1stwebdesigner. Today I’ll show you how to create a very nifty looking dynamic shadow with a few teaspoons of jQuery, a pinch of CSS and some transparent PNG’s as Base. I’ll explain every line of used code, so you can easily follow along and create your own awesome looking dynamic shadow powered by jQuery.

Introduction

When I first published my jQuery shadow experiment, I got a huge response from the community and a lot of people asked me, how I achieved this effect and if I’m going to write a tutorial for it – So here it is now!

If you want to follow along with the source files, you can download them by clicking here (*.zip archive). You can also take a look at the final demo here.

Step 1: Creating the transparent PNG’s

First we need to prepare all PNG files we’re going to use. We’ll need following image elements:

  1. The on/off switch (needs two states)
  2. The light source (in this case, a sexy light bulb – also with two states)
  3. The object which is going to drop the shadow (here it’s going to be a logo)
  4. and last but not least, the matching shadow of our logo

We’re going to use the CSS sprite technique for reducing HTTP requests. So we’ll need 3 images (otherwise we would need 6 separate images and twice as much HTTP requests).

1st PNG Image: The Light-Switch Sprite

Light-switch sprite

2nd PNG Image: The Light-Bulb Sprite

Light bulb sprite

3rd PNG Image: The Logo Sprite

Logo Sprite

I’m not going to explain how to create those images, as I’ll concentrate on the source code. If you want to use your own images, just make sure to save your images as PNG 24 , so your transparency gets saved too.

Step 2: Preparing our HTML, CSS & JS files

To make your files well-arranged, we’re going to create following folder structure for our files now:

Folder structure

The root folder (dynamicShadow) will contain our index.html with all layout containers inside of it. Inside of the img folder, you should put all three PNG image files you created or copied from step 1 above. Inside the css folder create a file named style.css. There we’ll style all layout elements we used in the html file. And the magic will happen inside of the js folder. There we’ll create a file named script.js. It will contain our jQuery JavaScript code.

If you have done those two steps above, we are now ready to go on and finally let the magic happen!

Step 3: Writing the HTML file with all containers we will use

First we need to include the files we created in the previous step, into the header part of our HTML.

First our stylesheet file:

<link type="text/css" rel="stylesheet" href="css/style.css" media="all" />

Now we’ll attach the latest version of jQuery itself and jQuery UI from Google’s AJAX Libraries repository:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>

Last but not least we need to attach our JavaScript file (script.js):

<script type="text/javascript" src="js/script.js"></script>

Our header should look something like this now:

<head>
	<link type="text/css" rel="stylesheet" href="css/style.css" media="all" />
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
	<script type="text/javascript" src="js/script.js"></script>
</head>

We can start with the body part of our HTML now:

We’re going to need following div’s with the same id’s for the next step, where we are going to style our containers.

<body>
	<div id="switch"></div>
	<div id="light-bulb" class="off"><div id="light-bulb2"></div></div>
	<div id="logo"></div>
	<div id="logosh"></div>
	<div id="infobox"><p>Please activate JavaScript!</p></div>
</body>

For explanation:

  1. “switch” will be our element, which is going to turn the light bulb on and off.
  2. ”light-bulb” and “light-bulb2” are our containers with the actual light bulb (I’ll explain later why we need it twice). Just make sure you don’t forget to add the “off” class to the outer light-bulb container.
  3. ”logo” is our element which is going to drop the shadow.
  4. ”logosh” will contain the appropriate shadow for the object.
  5. ”infobox” is just a bonus and not mandatory for our effect. It will contain some status messages. Additionally it contains a message for all (bad, bad) users, who are visiting your site with deactivated JavaScript. You can write them a message there. Take care at your diction, don’t be too evil to them ;).

Step 4: Let’s get some colors into our HTML file!

Now we’re ready to style our HTML with the CSS file we included into our header.

We will start with the info box. If you have chosen to include it, here is a styling suggestion:

body {
background:#3B4D61 url(../img/bg.jpg) repeat 0 0; }
#infobox {
	position:absolute;
	width:300px;
	bottom:20px;
	left:50%;
	margin-left:-150px;
	padding:0 20px;
	background:rgba(0,0,0,0.5);
	-moz-border-radius:15px;
	-webkit-border-radius:15px;
	z-index:999;
}
#infobox p {
	display:block;
	color:#D1D8DF;
	font:bold 15px/10px Tahoma, Helvetica, Arial, Sans-Serif;
	text-align:center;
}

For body, an image is used to enhance the effect of shadow.For the #infobox we are using some CSS3 to make it prettier. The background is black and 50% transparent with the awesome rgba attribute and the corners are rounded with a 15px wide diameter through the Mozilla and WebKit specific attributes. The box will be 340 pixels wide (300 + 2 x 20) and placed centered on the bottom of our page. With the z-index set to 999 it will be the topmost element in our page so it does not get covered from our logo, the shadow or the light bulb.

Next is our switch:

#switch {
	position:absolute;
	bottom:50px;
	left:50px;
	width:80px;
	height:120px;
	background:url(../img/light-switch.png) -80px 0 no-repeat;
	cursor:pointer;
	z-index:100;
}

It will be absolute positioned to the bottom left corner of our page. The backgrounds X position is set to –80px. There we are using the CSS sprite technique the first time. The cursor is going to be a pointer, so the user knows that he can click it. z-index to 100. The logo, the shadow and the light bulb must get a higher z-index, so they don’t disappear behind the switch.

Now let’s style our two light bulb containers:

#light-bulb {
	position:absolute;
	top:20%;
	left:70%;
	width:150px;
	height:150px;
	background:url(../img/lightbulb.png) -150px 0 no-repeat;
	cursor:move;
	z-index:800;
}
#light-bulb2 {
	width:150px;
	height:150px;
	display:none;
	background:url(../img/lightbulb.png) 0 0 no-repeat;
}

The backgrounds X position of the main light bulb container is set to –150px. This is the “turned off” state of our sprite-image. The “inner light bulb” (light-bulb2) is set to “top left” (0 0), so it is the “turned on” state of the sprite. Later we will animate the opacity of it from 0% to 100% and create a smooth blend effect from the on to the off state and reverse. z-index to 800: It will be above the switch, above the logo and above the shadow but behind the info box. The cursor attribute is set to “move”. This way the user will get a nice, OS-based cursor which tells him he can move this object around.

Our last two containers are the logo with his shadow:

#logo {
	position:absolute;
	top:40%;
	left:20%;
	width:450px;
	height:150px;
	background:url(../img/logo.png) 0 0 no-repeat;
	cursor:move;
	z-index:700;
}
#logosh {
	position:absolute;
	width:450px;
	height:150px;
	display:none;
	background:url(../img/logo.png) 0 -150px no-repeat;
	z-index:600;
}

The main logo containers gets also the “move” cursor and the background position is set to “top left” again. This will show the main part of our logo sprite. z-index to 700. It’ll be above the shadow and above the switch, but behind the light bulb and the info box.

The shadow container gets z-index of 600 and the backgrounds Y position is set to –150px. It’s the shadow part of our logo sprite-image.

If you came this wide, your index.html file should look something like this in your browser (of course only, if you used the same image files of this tutorial):

Dynamic shadow NoJS

Now let’s get this party started and add some spice to our page. We will write some JavaScript now!

Step 5: The magic starts to happen now!

Ok now let’s go with the interesting part of this whole tutorial. First we start with the jQuery’s main function:

$(function(){

});

This is the short hand code for jQuery’s document.ready(). Our whole script needs to be inside of this function, so it gets loaded, as soon as the DOM is ready.

Next we’ll define some variables and set the default text of our info box. The descriptions are inline as comments:

// shadow offset
var shadowOffset	=	1.08;

// the light switch
var lightswitch		=	$("#switch");

// outer light bulb
var lightbulb		=	$("#light-bulb");

// inner light bulb
var lightbulb2		=	$("#light-bulb2");

// center of light - X-axis
var lightCenterX	=	parseInt(lightbulb.width()/2);

// center of light - Y-axis
var lightCenterY	=	parseInt(lightbulb.height()/2);

// logo container
var logo			=	$("#logo");

// light and logo containers
var lightAlogo		=	$("#light-bulb, #logo");

// center of logo - X-axis
var logoCenterX		=	parseInt(logo.width()/2);

// center of logo - Y-axis
var logoCenterY		=	parseInt(logo.height()/2);

// shadow container
var logoshadow		=	$("#logosh");

// center of shadow - X-axis
var logoShdwCenterX	=	parseInt(logoshadow.width()/2);

// center of shadow - Y-axis
var logoShdwCenterY	=	parseInt(logoshadow.height()/2);

// info-box text container
var statustext		=	$("#infobox p");

// info-box default text
var defaulttxt		=	"Drag the light-bulb or the logo!";

// info-box text for hovering switch while state is "off"
var ontxt			=	"Let there be light!";

// info-box text for hovering switch while state is "on"
var offtxt			=	"Switch off the light!";

// set info-box text to default text
statustext.text(defaulttxt);

// start our main function (will be used later)
moveShadow();

For now, you can comment the last line out. moveShadow(); will be our main function which will change the position of the shadow.

Now let’s get dynamic and let us make the light bulb and the logo draggable. We’re going to use jQuery UI’s draggable interaction element to keep things easy.

// making the light and the logo draggable
lightAlogo.draggable({
	drag: function(event, ui){

		// change the statustext to "dragging + element id" state
		statustext.text("dragging " + $(this).attr("id"));

		// our main function which will move the shadow
		moveShadow();

	},
	stop: function(event, ui){

		// switching to default text when stopped dragging
		statustext.text(defaulttxt);

	}
});

While dragging, we’re going to set the status text of our info box to “dragging” + the id of the current element. So in our case it will be logo or light-bulb. When we release the mouse and stop dragging the current object, we revert the text to our default value.

Our two objects should now be draggable! Isn’t it easy with jQuery UI? :)
(There comes the “write less, do more” from, which is jQuery’s slogan.)

Again you can comment out the moveShadow(); function for now, if you want to try your code in the browser. This will be the main function which makes the dynamic shadow moving, while you drag either the light bulb or the logo.

With the following function, we’re going to change the default text of the info box to our on or off text when hovering:

// changing the info text when hovering the switch
lightswitch.hover(function(){

	if(lightbulb.hasClass("off")){

		// when lightbulb has the class "off" show this text
		statustext.text(ontxt);

	}else{

		// otherwise show this text
		statustext.text(offtxt);

	}
},function(){

	// hovering out will show the default text again
	statustext.text(defaulttxt);

});

If the light bulb has the class “off”, then show the “on text”, else show the “off text”. When hovering out, the default text will be shown again. Still easy, right?

Next is our function for calculating the opacity of our logo shadow, according to the distance of the light source. In our case the light bulb:

// calculating the shadow opacity according to the light bulb distance
function setOpacity(getDistance){

	if(lightbulb.hasClass("off")){

		// if the lightbulb has the class "off", opacity = 0 (no shadow)
		return 0;

	}else{

		// otherwise we calculate a suitable shadow opacity with this formula
		return (1.2 - getDistance /1000);

	}
}

If our light bulb has the class “off”, we’ll return “0”, which stands for zero opacity. No light, no shadow. Sounds logical, right? More interesting is the “else” part, where we’re going to use this formula “1.2 – getDistance / 1000” to calculate a shadow which will look quite good. getDistance /1000 will just move the decimal point 3 points to the left, giving us a usable number for the next calculation, where we are going to subtract it from 1.2 (which would be 120% theoretically).You can experiment with this value, if you are not satisfied with the results.

The next what we are going to do is to assign the things which should happen, when the user clicks on our light switch:

// assign the things, which should happen, when clicking the light switch
lightswitch.click(function(){

	// when the light bulb has the class "off" do following:
	if(lightbulb.hasClass("off")){

		// first remove the class "off"
		lightbulb.removeClass("off");

		// change the background position of the CSS sprite
		lightswitch.css("backgroundPosition","0 0");

		// showing the shadow of the logo with a fading animation
		logoshadow.stop().fadeTo(750,setOpacity(shadowDistance));

		// fade in the inner light bulb container (light is turned on!)
		lightbulb2.stop().fadeTo(750,1);

		// changing the status text to the "off text"
		statustext.text(offtxt);

	// else do following:
	}else{

		// adding the class "off"
		lightbulb.addClass("off");

		// move the background position of the switch back to original position
		lightswitch.css("backgroundPosition","-80px 0");

		// fade out the logo shadow
		logoshadow.stop().fadeTo(750,0);

		// fade out the turned on light (no more lights now)
		lightbulb2.stop().fadeTo(750,0);

		// changing the status text to the "on text"
		statustext.text(ontxt);

	}
});

A few things are happening now. Let’s get through it line by line.

First we need to differentiate if the lights should be turned on or off. For this we will check once again if the light bulb has the class “off” or not. If it has it, we’ll do following:

  1. We will remove it right again.
  2. Then we make use of our sprite image of the light switch and move it to the “on” position, which is “0 0″ / “top left”.
  3. After this we are going to fade in the shadow of the logo. We are doing this with the setOpacity function, described before. For now you have to change “shadowDistance” to “1”, if you want to try it. We will get the variable “shadowDistance” in the next function.
  4. Last things to do is to fade in our inner light bulb which is positioned via our CSS to get the “energized” part of the sprite image
  5. and change the status text to the “off state”.

If the light bulb has not a class named “off”, we will do the opposite of above which is following:

  1. add class “off” to our light bulb
  2. move the image of the light switch up by 80 pixels, so it is turned off again
  3. fade out the shadow
  4. fade out the inner light bulb (the lighten up one)
  5. and changing the status text to the “on state”

The last function we need is finally the one, which will move our shadow (and probably the most interesting one):

// the main function - our shadow mover
function moveShadow(){

	// save the current X position of the light bulb
	lightX			=	parseInt(lightbulb.offset().left) + lightCenterX;

	// save the current Y position of the light bulb
	lightY			=	parseInt(lightbulb.offset().top) + lightCenterY;

	// save the current X position of the logo
	logoX			=	parseInt(logo.offset().left) + logoCenterX;

	// save the current Y position of the logo
	logoY			=	parseInt(logo.offset().top) + logoCenterY;

	// save the value how far the logo is away from the light bulb on the X-axis
	distanceX		=	logoX - lightX;

	// save the value how far the logo is away from the light bulb on the Y-axis
	distanceY		=	logoY - lightY;

	// calculating and saving the value of the square root of those two distance values
	distance		=	Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2));

	// calculating and saving the shadow distance with the offset we defined in our variables
	shadowDistance	=	distance * shadowOffset;

	// preparing the CSS value to put into the "left" attribute of the shadow container
	shadowPosLeft	=	(distanceX / distance * shadowDistance + lightX - logoShdwCenterX) + "px";

	// preparing the CSS value to put into the "top" attribute of the shadow container
	shadowPosTop	=	(distanceY / distance * shadowDistance + lightY - logoShdwCenterY) + "px";

	// finaly using the results of all above calculations to position our shadow and set the opacity
	logoshadow.css({ "left": shadowPosLeft, "top": shadowPosTop, "opacity": setOpacity(shadowDistance) });

}

This may looks a little bit weird and strange to you on the first sight, but it’s really not so difficult to understand and I used only some basic math formula for the calculations which I will describe you now.

Let’s get through it, line by line again:

  1. lightX: Getting the current X position of our light bulb
  2. lightY: Getting the current Y position of our light bulb
  3. logoX: Same like 1. only with the logo container
  4. logoY: Same like 2. only with the logo container
  5. distanceX: Calculating how far the logo is away from the light bulb on the X-axis
  6. distanceY: Calculating how far the logo is away from the light bulb on the Y-axis
  7. distance: Calculating the square root of distanceX and distanceY using the Math.sqrt(); function and for the two values the Math.pow(); function, which stands for exponential power. The first parameter, in our case distanceX or distanceY is the parameter for the base and the second parameter stands for the power. For making it clear: On the paper you would write: distanceX² and distanceY²
  8. shadowDistance: Multiplying the actual distance with the offset we defined at the top of our script where the variables are defined. We used this variable on click function of the light switch. So if you changed “shadowDistance” to “1”, you can now change it back to this variable.
  9. shadowPosLeft: Making the left offset of the shadow ready, to use it in our last line.
  10. shadowPosTop: Making the top offset of the shadow ready, to use it in our last line.
  11. logoshadow.css(): finally we are changing the CSS of our shadow container so it gets correct positioned and has the proper opacity

That’s it!

The last thing you need to do is to uncomment the moveShadow(); function twice (only if you have commented it out). At first at the variables section and at last in the jQuery UI’s draggable function.

Your shadow is now dynamic positioned and also has a cool looking dynamic opacity, depending on the distance and position of both: The light bulb and the logo.

I hope you liked this tutorial and could follow it step by step. If you’ve done everything correctly, you should have ended up with something like this: DEMO.

If you had some troubles with any step or need further instructions or help, feel free to write your question into the comments section of this post so I can take a look at your question and help you out!

Thanks for reading and have fun trying and using it in your next project!

Daniel Kurdoghlian

Daniel Kurdoghlian is a freelance web designer, web developer and graphics artist living and working in Vienna (Austria). He is also founder of PushingPixels.at, a new media company specialized in web design, print design and photography. He's also co-founder of redeemoid, a service for people, who need download codes for their digital goods. If you want to get in contact with him, you can visit his vCard or just drop him a line through Twitter.

15 Smart Tools To Help You Build Your Freelance Business

Discover the awesome tools we use in making our clients comfortable and happy in learning new things every day.

Download Now

Comments

  1. Darren says

    Amazing tut! I already have a light bulb in my port can’t wait to implement something so dynamic and artistic as this. Thank you for the tut! :D

  2. Orien says

    Wooo .. it’s wonderfull..excuse me, I’ll practice on my blog… but, maybe you can process again to make a trick where nufty dynamic shadow can be used as energy savers trick to a blog, I thought it would be very very cool

  3. Anup says

    The tutorial is Demonstrated very clearly. I liked the tutorial plus i also need this for my project.

    I also solved the IE issue by adding DD_belatedPNG_0.0.8a.js file, And added one line of code in the tutorial’s script file as follows :-

    DD_belatedPNG.fix(‘#light-bulb, #light-bulb2′);

    Thank You for this Nice tutorial…..!!

  4. skyruler says

    Really good work! but in internet explorer, bad display. what can i do to display in internet explorer very well?

  5. Wyrd says

    Great tutorial, I have always had a bit of a problem with doing things like this. In retrospect it looks like it was the CSS that I was messing up because admittedly, I don’t really know the language. I’ll try adding some of your ideas and see if my next project comes out better.

    Thanks.

  6. dave says

    Great tutorial! If someone wants to post a version of this working in IE, would be appreciated. IE’s horrendous support for transparent PNGs has been driving me crazy for years–can’t believe it’s still not supported!

    • msherburne says

      You should try to use DD_belatedPNG.js for your issue with PNG files in IE

  7. says

    Hi,

    This is really awesome thought, you are really a star – since this article will prove that we can create awesome plugins and web applications using jQuery, you really proved it, I am going to write about this one in my website.

    Cheers! you rock!
    Vivek [Founder of http://www.developersnippets.com

  8. says

    Wow.. I finally found this great tutorial! Going to look more closer into it this weekend.
    I blame you Daniel as you didn’t tell me about this cool tutorial earlier :P

  9. Avinash says

    Nice Tutorial!!
    I really appreciate the way you explain the code!!

    Have a nice day :)

    Congrats & Best Regards
    ~Avinash

  10. says

    You’re welcome!
    I’m glad you liked it – Looking forward to your project, where you’re going to use it! Would be nice if you tell us when you’re finished! :)

  11. says

    You can’t replace Flash every time with JavaScript – but whenever it’s possible, I will sure do so! :)

    Also the SEO aspect is the same as with every other page, not using Flash. It always depends how good it is programmed and optimized.
    A Flash page can have a just as good SEO like every other page too!

  12. Melody says

    This is a super cool idea, nice way to add a little character to a design..

  13. Angele Manoukian says

    Hi Daniel, inchbes es pashas, im khelkis chi hanir ays inch vor erer es payts kidem vor shad khelatsi pan men e, yev vesdah em vor shad aghvor kuyd me bidi enes or me shad medz vesdahoutyoun ounim kou verat, Go my genius nephew!! Love u Bachigner

  14. Amberly | Web Designer says

    Very interesting tutorial.
    I am waiting for a moment when jQuery will totally replace flash, then I will be happy.

    • says

      I’m totally working into the direction to replace as much flash as possible – but still I don’t think that complex flash in general is getting ever replaced by JavaScript.
      Tho’, with the html5 canvas element, a lot can be achieved already!
      Get ready for some advanced canvas tutorials too in near future! :)

  15. says

    Very nice tutorial! I think I will find a way to incorporate it into http://theeasyapi.com. We are always on the lookout for new additions to the website interface. Our main business is offering one easy to use API that accesses other API’s and then standardizes the output. Really great tutorial and I’ll pass it along to my designers and see what they can come up with to utilize it.

    Nice work!

    • says

      I hope everything is written clear enough, so your designing team can easily follow along this tutorial!
      I’m curious if and where they’re going to use this effect – would be nice to see it elsewhere :)

    • says

      I’m glad you liked it!

      To make IE render this correct, you need to use one of the “PNG-hacks”.. The problem appears because of the (retarded) IE can’t render PNG’s with transparency and I didn’t wanted to mess my code up because of a buggy browser.

      • Carl says

        Your comment surprises me because you go to great lengths in javascript to create a great effect — then refuse to write a couple more lines for the second most popular browser-version (behind IE8 and ahead of Firefox 3.6) on the planet. I feel sad for you.

    • says

      I believe your reply is based on IE6 not natively rendering PNGs, which you would have to use the “filter” hack. However, IE7 and 8 do render PNGs with alpha natively and that begs the question: why does this demo not render properly in IE7 or 8?

      I took your shadow file and did a local test with it against a colored background and had no issues with transparency…quite odd.

      • says

        Hi Darrell!

        First of all, thank you for your feedback!

        ..and yes, you’re right – the fix I was speaking of, was regarding the wrong rendering in IE6, not IE6+

        As you see in my demo, I’m using a sprite image which is correctly rendering in IE7 and IE8 – the problem is only appearing to the second elements (#logosh & light-bulb2) which are hidden by default and fading in when the switch is clicked.

        This happens because of a known bug of jQuery (+UI) itself which, unfortunately, is not yet resolved.
        jQuery UI Bug-Tracker Ticket: http://dev.jqueryui.com/ticket/3791
        jQuery Bug Tracker-Ticket: http://dev.jquery.com/ticket/5946

        ..However – What works are semi-transparent PNG8’s (yes you can create them semi-transparent) – there are also other workarounds for this known problem – but the easiest is this.

        Here you have some resource-links if you need further help or sources:
        stackoverflow post: http://j.mp/bB5lQJ
        pngquant – command-line utility to create semi-transparent 8bit PNG’s: http://j.mp/97xpNS

        Another workaround for this problem would be to use normal img tags instead of the sprited-background-image technique and the method described here: http://j.mp/d37CY8 (take also a look on the comments there)

        So, my conclusion to the IE-behavior itself: IE still sucks (no matter what version – they all simply suck, from version 1.0 through version 8.0)

        Hope this answered your question Darrell!