Using the DOM to Build Dynamic Shadows with JavaScript and CSS - Creating dynamic shadows with the DOM
(Page 3 of 4 )
Indeed, it’s very easy to build dynamic shadows that can be attached to a particular web page element, by using a combination of DOM scripting, and some CSS styles as well.
In simple terms, this DOM-driven technique involves simply adding on the fly a gray-colored DIV to the element that needs to be shadowed. In this case, the DIV is absolutely positioned with respect to the targeted element, in this manner achieving a neat shadowing effect.
Does this sound rather confusing to you? It really isn't. However, to clarify how this approach works, take a look at the signature of the following JavaScript function, which appends dynamically, via the DOM, a shadow to a selected web page element.
The definition of this function is as follows:
function addShadow(){
var mainCont=document.getElementById('maincontainer');
if(!mainCont){return};
var shadow=document.createElement('div');
mainCont.appendChild(shadow);
shadow.id='shadow';
}
That was really short, right? However, despite its brief definition, the above “addShadow()” JavaScript function does good work. It first selects a “maincontainer” DIV, and then it creates the dynamic shadow for it. Finally, the function inserts it into the web document tree via the DOM. At the end of this process, the “shading” DIV is appropriately positioned.
In addition, the above “addShadow()” function should be logically invoked after the web page has been loaded, in the following way:
window.onload=function(){
if(document.createElement&&document.getElementById&&document.getElementsByTagName){
addShadow();
}
}
Finally, you should take a look at the screen shot below, which illustrates the look and feel of the selected DIV, after adding to it the pertinent dynamic shadow:

Did you already grasp the logic that stands behind building dynamic shadows with the DOM and CSS? I bet you have! As you saw before, the shading procedure is reduced to adding to a given DIV, another one (the shadow), which is absolutely positioned within the web page.
However, the previous JavaScript function would be rather incomplete if I didn't show you how it can be linked to the corresponding CSS styles and the structural markup. Therefore, in the section to come I’m going to show you the complete source code of this extensible shading application.
All you have to do is click on the link below and keep reading.
Next: The shading application’s full source code >>
More JavaScript Articles
More By Alejandro Gervasio