Keilly: Resizing Text Dynamically

Monday, August 6, 2007

Resizing Text Dynamically

In the latest version of the ListenAgain widget the text shrinks and descriptions disappear when the widget is resized to a small size. I think this is quite a nice effect and especially useful in Dashboard where space is very limited.

The trick is to use JavaScript to manipulate the CSS style when the widget resizes.
The hardest thing I found was to find the correct style sheet object. The following bit of code should do the hard work and return the CSS object with the matching name.

function getStyleClass(className)
{
for(var s=0; s < document.styleSheets.length; s++)
{
var ret = getStyleClassFromRules(className,
document.styleSheets[s].cssRules);
if (ret != null)
return ret;
}
return null;
}

function getStyleClassFromRules(className, cssRules)
{
for(var r=0; r<cssRules.length; r++)
{
if (cssRules[r].selectorText != null)
{
if (cssRules[r].selectorText == className)
return cssRules[r];
}
else if (cssRules[r].styleSheet)
{
var ret = getStyleClassFromRules(className,
cssRules[r].styleSheet.cssRules);
if (ret != null)
return ret;
}
}
return null;
}
So now in your resize method, grab the CSS Object for the object to shrink and tweak it's style: e.g. To find the style for ".articlebody" and change it's look...

var descStyle = getStyleClass(".articlebody");
if (descStyle != null)
{
if (y < 280)
descStyle.style.display = "none"; // hide
else
descStyle.style.display = "block"; // show

if (x < 245)
descStyle.style.fontSize = "11px"; // small
else if (x < 280)
descStyle.style.fontSize = "12px"; // larger
else
descStyle.style.fontSize = "13px"; // largest
}

Of course there are loads more style options to change, and from here lots of cool effects are possible. For example, add a simple timer and slowly change an objects opacity to make it fade in or out; or grow and shrink an image as the mouse moves over it.

No comments: