Client Side Scripts Part 2: Flex Style Animations in DHTML
Previously, I presented a framework for using client side events. Now, just to get your imaginative juices flowing, here is a sample that illustrates how you could easily implement a Flex style animation framework to add life to your UIs. Imagine being able to add rich animations to your UI with something as simple as: “<Animate Event="OnClick" ControlToModify="MyControl" PropertyToModify="Width" StartValue=“0“ EndValue=“400“ Duration=“1000“ Relative=“True“ />“. Sound interesting... read on...:
public class AnimateClientScript : ClientScript
{
string controlToModify;
public string ControlToModify
{
get
{
return controlToModify;
}
set
{
controlToModify = value;
}
}
string propertyToModify;
public string PropertyToModify
{
get
{
return propertyToModify;
}
set
{
propertyToModify = value;
}
}
int duration;
public int Duration
{
get
{
return duration;
}
set
{
duration = value;
}
}
string startValue;
public string StartValue
{
get
{
return startValue;
}
set
{
startValue = value;
}
}
string endValue;
public string EndValue
{
get
{
return endValue;
}
set
{
endValue = value;
}
}
bool relative;
public bool Relative
{
get
{
return relative;
}
set
{
relative = value;
}
}
public override string GenerateScript()
{
Control c = Parent.Page.FindControl(ControlToModify);
WebControl wc = c as WebControl;
StringBuilder builder = new StringBuilder();
string cID = c.ClientID.Replace(":","_");
string property = "";
if(propertyToModify == "Width")
{
property = "style.width";
}
builder.AppendFormat("document.all['{0}'].reps = 0;",cID);
if(relative)
{
builder.AppendFormat("document.all['{0}'].initialValue = parseInt(document.all['{0}'].{1}.replace('px',''))+{2};", cID, property, startValue);
}
else
{
builder.AppendFormat("document.all['{0}'].initialValue = {1};", cID, startValue);
}
int timeout = duration / 50;
builder.AppendFormat(@"document.all['{0}'].intervalID = setInterval('if(document.all[\'{0}\'].reps*{5} < {4})” +
@“{{ document.all[\'{0}\'].{1} = document.all[\'{0}\'].initialValue + ({2}-{3})*“ +
@“(document.all[\'{0}\'].reps*{5})/{4}; document.all[\'{0}\'].reps++; }} else “ +
@“{{ clearInterval(document.all[\'{0}\'].intervalID); }}', {5});", cID, property,
endValue, startValue, duration, timeout);
return builder.ToString();
}
}
Keep in mind this sample is not intended to be complete, there are lots of little additions that would need to be made to get this fully functional (such as support for multiple concurrent animations and saving those vals back upon postback), but it does at least give you the idea of how a framework like this could really beef up your UI with zero client side script coding on the part of its consumers. Don't you wish I was on the ASP.NET team ;-).