I was on the jQuery website the other day reading the documentation and as I neared end of the page I noticed one of the footer links appeared to have a text-shadow. For whatever reason I decided to inspect the element with Firebug, only to discover it wasn't using CSS3's text-shadow property. What I found was the text was actually duplicated and layered on top of the exact same text, but slightly offset.
This isn't exactly a new technique, I mean check out You're the Man Now Dog for probably one of the earliest examples. In any case, IE6, IE7 & IE8 do not support the CSS3 text-shadow property, and the only form of shadowing they support is the proprietary shadow filter. So I figured, why not make a jQuery plugin where you can just apply this to an element and have it automatically do all the work for you while still working in IE6, IE7 & IE8.
HTML Setup
Below is the HTML I'll apply the text shadow to:
<p><span class="shadow-me">Text Shadow</span></p>
Javascript Setup
Here is the basic plugin call. The first parameter is the color of the shadow, the second the x-offset and the third the y-offset.
$(document).ready(function(){
$(".shadow-me").textShadow("#000",1,1);
});
jQuery Plugin
Finally, below is the jQuery plugin I wrote. The parent variable basically creates a random ID that I use to target the jQuery created element. I then wrap the target element in a DIV which is used as a position: relative; container. Next I set the height of that container so that it overflows correctly.
After that, I create the additional HTML element to act as a faux shadow and position it according to the parameters.
(function ($) {
$.fn.textShadow = function(shadowcolor,x,y) {
return this.each(function(i){
var parent = "tsw-" + Math.floor(Math.random()*100000);
//Create container
$(this).wrap('<div class="text-shadow-wrapper" id="' + parent + '"></div>');
//Set height of container so that it properly overflows
$("#" + parent).css("height", $(this).css("font-size")); //Math.abs()??
//Add text-shadow class to initial element
$(this).addClass("text-shadow");
//Adds shadow HTML element
$(this).before('<span class="shadow">' + $(this).text() + '</span>');
//Positions shadow HTML element
$("#" + parent + " .shadow").css({left: x, top: y, color: shadowcolor});
});
};
})(jQuery);
Examples
Below are a few examples I created with this technique. You can also view these on my demo page to see what's going on behind the scenes.
Todos
There's a few things I'd need to improve on the plugin before it gets used in any production environment. First the shadow loses any specific font-styling applied directly to the original text. One could craft their selectors in a way that wouldn't make this a problem. Also the plugin could be improved to check against the original text's font properties and apply those to the shadow. Finally this doesn't appear to work very well if placed in between a large amount of a text. It works best as a page heading or in a nav.