Animation Effects in ASP.NET using jQuery

Exclusive offer: get 50% off this eBook here
ASP.NET jQuery Cookbook

ASP.NET jQuery Cookbook — Save 50%

Over 60 practical recipes for integrating jQuery with ASP.NET

$26.99    $13.50
by Sonal Aneel Allana | May 2011 | .NET

jQuery offers many useful utilities to achieve animation effects, thus empowering developers to build rich animated pages for a better interactive experience for the web users. This article looks into various interesting animation effects that can be achieved using jQuery.

In this article by Sonal Aneel Allana, author of ASP.NET jQuery Cookbook, we will cover:

  • Enlarging text on hover
  • Creating fade effect on hover
  • Sliding elements on a page
  • Preventing animation queue buildup
  • Animating a panel
  • Chaining animations together

 

ASP.NET jQuery Cookbook

ASP.NET jQuery Cookbook

Over 60 practical recipes for integrating jQuery with ASP.NET

        Read more about this book      

(For more resources on ASP.NET, see here.)

Introduction

Some useful inbuilt functions in jQuery that we will explore in this article for achieving animation effects are:

  • animate ( properties, [ duration ], [ easing ], [ complete ] ):
    This method allows us to create custom animation effects on any numeric css property. The parameters supported by this method are:
    • properties: This is the map of css properties to animate, for e.g. width, height, fontSize, borderWidth, opacity, etc.
    • duration: This is the duration of the animation in milliseconds. The constants slow and fast can be used to specify the durations, and they represent 600 ms and 200 ms respectively.
    • easing: This is the easing function to use. Easing indicates the speed of the animation at different points during the animation. jQuery provides inbuilt swing and linear easing functions. Various plugins can be interfaced if other easing functions are required.
    • complete: This indicates the callback function on completion of the animation.
  • fadeIn ( [ duration ], [ callback ] ):
    This method animates the opacity of the matched elements from 0 to 1 i.e. transparent to opaque. The parameters accepted are:
    • duration: This is the duration of the animation
    • callback: This is the callback function on completion of the animation
  • fadeOut( [ duration ], [ callback ] ):
    This method animates the opacity of the matched elements from 1 to 0 i.e. opaque to transparent. The parameters accepted are:
    • duration: This is the duration of the animation
    • callback: This is the callback function on completion of the animation
  • slideUp( [ duration ], [ callback ] ):
    This method animates the height of the matched elements with an upward sliding motion. When the height of the element reaches 0, the css property display of the element is updated to none so that the element is hidden on the page. The parameters accepted are:
    • duration: This is the duration of the animation
    • callback: This is the callback function on completion of the animation
  • slideDown( [ duration ], [ callback ] ):
    This method animates the height of the matched elements from 0 to the specified maximum height. Thus, the element appears to slide down on the page. The parameters accepted are:
    • duration: This is the duration of the animation
    • callback: This is the callback function on completion of the animation
  • slideToggle( [ duration ], [ callback ] ):
    This method animates the height of the matched elements. If the element is initially hidden, it will slide down and become completely visible. If the element is initially visible, it will slide up and become hidden on the page. The parameters accepted are:
    • duration: This is the duration of the animation
    • callback: This is the callback function on completion of the animation
  • jQuery.fx.off:
    If there is a need to disable animations because of a resource constraint or due to difficulties in viewing the animations, then this utility can be used to turn off the animation completely. This is achieved by setting all animated controls to their final state.
  • stop ( [ clearQueue ], [ jumpToEnd ] ):
    This method stops the currently running animations on the page. The parameters accepted are:
    • clearQueue: This indicates whether any queued up animations are required to be cleared. The default value is false.
    • jumpToEnd: This indicates if the current animation is to be cleared immediately. The default value is false.

In this article, we will cover some of the animation effects that can be achieved in ASP.NET using the capabilities of jQuery.

Getting started

  1. Let's start by creating a new ASP.NET website in Visual Studio and name it Chapter5.
  2. Save the jQuery library in a script folder js in the project.
  3. To enable jQuery on any web form, drag-and-drop to add the following to the page:
    <scriptsrc='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="js/jquery-1.4.1.js" type="text/javascript"></script>

Now let's move on to the recipes where we will see different animation techniques using jQuery.

Enlarging text on hover

In this recipe, we will animate the font size of text content on hover.

Getting ready

  1. Add a new web form Recipe1.aspx to the current project.
  2. Create a Css class for the text content that we want to animate. The font size specified in the css Class is the original font size of the text before animation is applied to it:

    .enlarge
    {
    font-size:12.5px;
    font-family:Arial,sans-serif;
    }

  3. Add an ASP.NET Label control on the form and set its Css Class to the preceding style:
    <asp:LabelCssClass="enlarge"runat="server">Lorem ipsum dolor sit
    ...............</asp:Label>

Thus, the ASPX markup of the form is as follows:

<form id="form1" runat="server">
<div align="center">
Mouseover to enlarge text:<br />
<fieldset id="content" style="width:500px;height:300px;">
<asp:LabelCssClass="enlarge" runat="server">Lorem ipsum dolor
sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</
asp:Label>
</fieldset>
</div>
</form>

Thus, initially, the page will display the Label control as follows:

ASP.NET jQuery Cookbook

We will now animate the font size of the Label on hover on the containing fieldset element.

How to do it…

  1. In the document.ready() function of the jQuery script block, retrieve the original font size of the Label:
    var origFontSize = parseFloat($(".enlarge").css('font-size'));

    The parseFloat() function takes in an input string and returns the first floating point value in the string. It discards any content after the floating point value. For example, if the css property returns 12.5 px, then the function will discard the px.

  2. Define the hover event of the containing fieldset element:
    $("#content").hover(
  3. In the mouseenter event handler of the hover method, update the cursor style to pointer:
    function() {
    $(".enlarge").css("cursor", "pointer");
  4. Calculate the maximum font size that we want to animate to. In this example, we will set the maximum size to thrice the original:
    var newFontSize = origFontSize * 3;
  5. Animate the fontSize css property of the Label in 300 ms:
    $(".enlarge").animate({ fontSize: newFontSize }, 300);
    },
  6. In the mouseleave event handler of the hover method, animate the fontSize to the original value in 300 ms as shown:

    function() {
    $(".enlarge").animate({ fontSize: origFontSize }, 300);
    }
    );

Thus, the complete jQuery solution is as follows:

<script language="javascript" type="text/javascript">
$(document).ready(function() {
var origFontSize = parseFloat($(".enlarge").css('fontsize'));
$("#content").hover(
function() {
$(".enlarge").css("cursor", "pointer");
var newFontSize = origFontSize * 3;
$(".enlarge").animate({ fontSize: newFontSize }, 300);
},
function() {
$(".enlarge").animate({ fontSize: origFontSize },
300);
}
);
});
</script>

How it works…

Run the web form. Mouseover on the fieldset area. The text size will animate over the stated duration and change to the maximum specified font size as displayed in the following screenshot:

ASP.NET jQuery Cookbook

On removing the mouse from the fieldset area, the text size will return back to the original.

Creating a fade effect on hover

In this recipe, we will create a fade effect on an ASP.NET Image control on hover. We will use the fadeIn and fadeOut methods to achieve the same.

Getting ready

  1. Add a new web form Recipe2.aspx to the current project.
  2. Add an image control to the form:
    <asp:Image src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="images/Image1.jpg" ID="Image1" runat="server" />
  3. Define the properties of the image in the css:

    #Image1
    {
    width:438px;
    height:336px;
    }

  4. Thus, the complete ASPX markup of the web form is as follows:

    <form id="form1" runat="server">
    <div align="center">
    Mouseover on the image to view fade effect:
    <fieldset id="content" style="width:480px;height:370px;">
    <br />
    <asp:Image src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="images/Image1.jpg" ID="Image1" runat="server" />
    </fieldset>
    </div>
    </form>

  5. On page load, the image is displayed as follows:

    ASP.NET jQuery Cookbook

We will now create a fade effect on the image on hover on the containing fieldset area.

How to do it…

  1. In the document.ready() function of the jQuery script block, define the hover event on the containing fieldset area:
    $("#content").hover(
  2. In the mouseenter event handler of the hover method, update the cursor to pointer:

    function() {
    $("#Image1").css("cursor", "pointer");

  3. Apply the fadeOut method on the Image control with an animation duration of 1000 ms:

    $("#Image1").fadeOut(1000);
    },

  4. In the mouseleave event handler of the hover method, apply the fadeIn method on the Image control with an animation duration of 1000 ms:

    function() {
    $("#Image1").fadeIn(1000);
    }
    );

Thus, the complete jQuery solution is as follows:

<script language="javascript" type="text/javascript">
$(document).ready(function() {
$("#content").hover(
function() {
$("#Image1").css("cursor", "pointer");
$("#Image1").fadeOut(1000);
},
function() {
$("#Image1").fadeIn(1000);
}
);
});
</script>

How it works...

Run the web page. Mouseover on the Image control on the web page. The image will slowly fade away as shown in the following screenshot:

ASP.NET jQuery Cookbook

On mouseout from the containing fieldset area, the image reappears.

Sliding elements on a page

In this recipe, we will use the slideUp and slideDown methods for achieving sliding effects on an ASP.NET panel.

Getting ready

  1. Add a new web form Recipe3.aspx in the current project.
  2. Add an ASP.NET panel to the page as follows:

    <asp:Panel class="slide" runat="server">
    Sliding Panel
    </asp:Panel>

  3. The css class for the panel is defined as follows:

    .slide
    {
    font-size:12px;
    font-family:Arial,sans-serif;
    display:none;
    height:100px;
    background-color:#9999FF;
    }

  4. Add a button control to trigger the sliding effect on the panel:
    <asp:Button ID="btnSubmit" runat="server" Text="Trigger Slide" />
  5. Thus, the complete ASPX markup of the web form is as follows:
    <form id="form1" runat="server">
    <div align="center">
    <fieldset style="width:400px;height:150px;">
    <asp:Button ID="btnSubmit" runat="server" Text="Trigger Slide" />
    <br /><br/>
    <asp:Panel class="slide" runat="server">
    Sliding Panel
    </asp:Panel>
    </fieldset>

    </div>
    </form>

On page load, the page appears as shown in the following screenshot:

ASP.NET jQuery Cookbook

We will now use jQuery to slide up and slide down the panel.

How to do it…

  1. In the document.ready() function of the jQuery script block, define the click event of the button control:
    $("#btnSubmit").click(function(e) {
  2. Prevent default form submission:
    e.preventDefault();
  3. Check if the ASP.NET panel control is hidden:
    if ($(".slide").is(":hidden"))

    The jQuery selector :hidden selects matched elements that are hidden on the page.

  4. If yes, then slide down the panel until its height reaches the maximum (100 px) defined in the css property.
    $(".slide").slideDown("slow");
  5. If the panel is initially visible then slide up so that its height slowly reduces until it becomes 0 and the panel disappears from the page:

    else
    $(".slide").slideUp("slow");
    });

Thus, the complete jQuery solution is as follows:

<script language="javascript" type="text/javascript">
$(document).ready(function() {
$("#btnSubmit").click(function(e) {
e.preventDefault();
if ($(".slide").is(":hidden"))
$(".slide").slideDown("slow");
else
$(".slide").slideUp("slow");
});
});
</script>

 

ASP.NET jQuery Cookbook Over 60 practical recipes for integrating jQuery with ASP.NET
Published: April 2011
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

 

        Read more about this book      

(For more resources on ASP.NET, see here.)

How it works…

Run the page. Initially, the panel is invisible. Now click the Trigger Slide button. The panel height is animated until it becomes completely visible as follows:

ASP.NET jQuery Cookbook

On clicking the button once again, the panel height is animated again so that it decreases until it disappears from the page.

ASP.NET jQuery Cookbook

There's more…

The same effect can also be achieved using the slideToggle method on the panel as follows:

$(".slide").slideToggle("slow");

Preventing animation queue buildup

If multiple animation events are triggered on an ASP.NET form simultaneously, jQuery queues the animations and executes the complete queue. This might sometimes lead to undesirable results. In this recipe, we will see the impact of an animation queue buildup and how we can prevent the same.

Getting ready

  1. Add a new web form Recipe4.aspx to the current project.
  2. Define a css style for a simple menu control:

    .menuitem
    {
    background-color:Gray;
    font-weight:bold;
    color:White;
    text-align:center;
    width:100px;
    height:50px;
    cursor:pointer;
    }

The complete ASPX markup of the web form is as follows:

<form id="form1" runat="server">
<div align="center">
<table border="0" cellpadding="3" cellspacing="3">
<tr>
<td class="menuitem">Menu Item 1</td>
<td class="menuitem">Menu Item 2</td>
<td class="menuitem">Menu Item 3</td>
<td class="menuitem">Menu Item 4</td>
</tr>
</table>
</div>
</form>

On page load, the web form displays the menu items as shown in the following screenshot:

ASP.NET jQuery Cookbook

We will now animate the opacity of the menu items on mouseover:

How to do it…

  1. In the document.ready() function of the jQuery script block, define the hover event on the menu items using jQuery's css selector:
    $(".menuitem").hover(function(){
  2. In the mouseenter event handler of the hover method, animate the opacity of the menu items to 0.5:

    $(this).animate({opacity:0.5},"slow");
    },

  3. In the mouseleave event handler of the hover method, animate the opacity back to 1 i.e. opaque):

    function(){
    $(this).animate({opacity:1},"slow");
    });

Thus, the complete jQuery script is as follows:

<script language="javascript" type="text/javascript">
$(document).ready(function() {
//PART 1 - ANIMATION QUEUE BUILDUP
$(".menuitem").hover(function(){
$(this).animate({opacity:0.5},"slow");
},
function(){
$(this).animate({opacity:1},"slow");
});
});
</script>

Run the page and observe the behavior of the menu items.

Now, update the preceding script slightly to include the stop() method in the animation as follows:

<script language="javascript" type="text/javascript">
$(document).ready(function() {
//PART 2 - PREVENTING ANIMATION QUEUE BUILDUP
$(".menuitem").hover(function(){
$(this) .stop().animate({opacity:0.5},"slow");
},
function(){
$(this) .stop().animate({opacity:1},"slow");
});
});
</script>

Run the page again and observe the behavior of the menu items.

How it works…

During the first run, when the mouse is moved randomly over the menu items, the opacity level changes on mouseenter and mouseleave events on the respective target items. You will also notice that this effect queues up for each menu item that had mouseenter/mouseleave events triggered as shown in the following screenshot:

ASP.NET jQuery Cookbook

Even after moving the cursor away, jQuery continues to run the animations in the queue.

However, during the second run when the stop() method is called before initiating a call to the animate() method, stop() terminates all currently running animations by bringing the animated objects to the final state. As a result, only the opacity level of the target menu item changes on hover and the rest of the menu items are returned to an opaque state as demonstrated in the following screenshot:

ASP.NET jQuery Cookbook

Animating a panel

In this recipe, let's animate different properties of an ASP.NET panel such as width, height, opacity, font size, and border width simultaneously on a web page.

Getting ready

  1. Add a new web form Recipe5.aspx to the current project.
  2. Add an ASP.NET panel control to the form:

    <asp:Panel class="contentArea" runat="server">
    Lorem ipsum dolor sit amet, consectetuer adipiscing
    elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore
    magna aliquam erat volutpat.
    </asp:Panel>

  3. Set its css class as shown:

    .contentArea
    {
    font-size:12px;
    font-family:Arial,sans-serif;
    width:200px;
    height:100px;
    background-color:#9999FF;
    border:solid;
    }

  4. Add a button control to trigger the animation effect:
    <asp:Button ID="btnSubmit" runat="server" Text="Animate" />

Thus, the complete ASPX markup of the web form is as follows:

<form id="form1" runat="server">
<div align="center">
<fieldset style="width:550px;height:370px;">
<asp:Button ID="btnSubmit" runat="server" Text="Animate" />
<br /><br />
<asp:Panel class="contentArea" runat="server">
Lorem ipsum dolor sit amet, consectetuer adipiscing
elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna
aliquam erat volutpat.
</asp:Panel>
</fieldset>
</div>
</form>

Thus, on page load, the page appears as follows:

ASP.NET jQuery Cookbook

How to do it…

  1. In the document.ready() function of the jQuery script block, enable the button control explicitly on page load:
    $("#btnSubmit").removeAttr("disabled", "disabled");
  2. Define the click event of the button control:
    $("#btnSubmit").click(function(e) {
  3. Prevent default form submission:
    e.preventDefault();
  4. Use jQuery's css selector to retrieve the panel control and call the animate method providing a map of css properties to animate. Define the animation duration as slow:

    $(".contentArea").animate({
    opacity: 0.5,
    width: "500px",
    height: "280px",
    fontSize: "36px",
    borderWidth: "15px"
    }, "slow");

    The above map of css properties causes the panel control to animate to an opacity of 0.5, width of 500 px, height of 280 px, font size of 36 px, and border width of 15 px in a duration of 600 ms.

  5. Disable the button control at the end of the animation:

    $(this).attr("disabled", "disabled");
    });

Thus the complete jQuery solution is as follows:

<script language="javascript" type="text/javascript">
$(document).ready(function() {
$("#btnSubmit").removeAttr("disabled", "disabled");
$("#btnSubmit").click(function(e) {
e.preventDefault();
$(".contentArea").animate({
opacity: 0.5,
width: "500px",
height: "280px",
fontSize: "36px",
borderWidth: "15px"
}, "slow");
$(this).attr("disabled", "disabled");
});
});
</script>

How it works…

Run the web page. Click on the Animate button to kick start the animation effect. The page displays the panel control as follows at the end of the animation:

ASP.NET jQuery Cookbook

Chaining animations together

In this example, let's see how a sequence of animations can be chained together to create a continuous animation effect. We will also vary the speed of each animation in the sequence.

Getting ready

  1. Add a new web form Recipe6.aspx to the current project.
  2. Add an ASP.NET panel control to the form:
    <asp:Panel class="contentArea" runat="server">
    </asp:Panel>
  3. Sets its css class as follows:

    .contentArea
    {
    width:50px;
    height:50px;
    background-color:#9999FF;
    border:solid;
    position:relative;
    }

  4. Add a button control to the form to trigger the animation sequence:
    <asp:Button ID="btnSubmit" runat="server" Text="Animate" />

Thus, the complete ASPX markup of the form is as follows:

<form id="form1" runat="server">
<div align="center">
<fieldset style="width:550px;height:250px;">
<asp:Button ID="btnSubmit" runat="server" Text="Animate" />
<br /><br />
<asp:Panel class="contentArea" runat="server">
</asp:Panel>
</fieldset>
</div>
</form>

On load, the page will display the panel control as shown in the following screenshot:

ASP.NET jQuery Cookbook

We will now apply a series of sliding motion to the panel control by chaining the animation functions.

How to do it…

  1. In the document.ready() function of the jQuery script block, define the click event of the button control:
    $("#btnSubmit").click(function(e){
  2. Prevent default form submission:
    e.preventDefault();
  3. Retrieve the panel control using the jQuery css selector and animate the left offset and opacity of the panel control in 2000 ms:
    $('.contentArea').animate({left:"+=200", opacity: 0.8}, 2000)
  4. Chain another animation method to the one we just saw to animate the top offset and opacity of the panel control in 700 ms:
    .animate({top:"+=100", opacity:0.5},700)
  5. Chain another animation method to the one we just saw to animate the left offset and opacity of the panel control in 1200 ms:
    .animate({left:"-=400", opacity: 0.2},1200)
  6. Chain another animation method to the one we just saw to animate the top offset and opacity of the panel control in 700 ms:
    .animate({top:"-=100", opacity: 0.5},700)
  7. Chain another animation method to the one we just saw to animate the left offset and opacity of the panel control in 2000 ms:

    .animate({left:"+=200", opacity: 0.8},2000);
    });

Thus, the complete jQuery solution is as follows:

<script language="javascript" type="text/javascript">
$(document).ready(function() {
$("#btnSubmit").click(function(e){
e.preventDefault();
$('.contentArea').animate({left:"+=200", opacity: 0.8},
2000)
.animate({top:"+=100", opacity:0.5},700)
.animate({left:"-=400", opacity: 0.2},1200)
.animate({top:"-=100", opacity: 0.5},700)
.animate({left:"+=200", opacity: 0.8},2000);
});
});
</script>

How it works…

Run the web page. Click on the Animate button. You will notice that the panel control goes through the following sequence of animations:

  1. Slides to the right by 200 px.
  2. Slides to the bottom by 100 px as captured:

    ASP.NET jQuery Cookbook

  3. Slides to the left by 400 px as displayed next:

    ASP.NET jQuery Cookbook

  4. Slides to the top by 100 px as displayed next:

    ASP.NET jQuery Cookbook

  5. Slides to the right by 200 px.

Thus, the panel returns back to the original position after the sequence of animation is completed. Notice that the opacity levels and the duration of the animation differs from one step to the next.

Summary

In this article we took a look at various interesting animation effects that can be achieved using jQuery. We learnt how to apply different types of animation effects to ASP. Various effects such as fading, sliding, enlarging, and so on were covered in this article. The article also demonstrated animation chaining and prevention of animation queue buildup.


Further resources on this subject:


ASP.NET jQuery Cookbook Over 60 practical recipes for integrating jQuery with ASP.NET
Published: April 2011
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

About the Author :


Sonal Aneel Allana

Sonal Aneel Allana is a Senior Technical Consultant with Accentiv' SurfGold, Singapore. She has over a decade of experience in building web and desktop solutions in Microsoft technologies. She has worked with government agencies, credit bureaus, banks, financial institutions, and multinationals, delivering high-end customized solutions to meet their needs. She has worked on applications ranging from core banking software and B2B links to content management, workflow, and loyalty engines.

From time to time, she has also taken up the role of project lead and has carried numerous projects from conceptualization through implementation successfully. In addition to her experience in Microsoft technologies, she is well versed in the J2EE and LAMP platforms.

She holds a Master's degree in Computer Science from the National University of Singapore and a Bachelor's degree in Computer Engineering from Mumbai University. She is also passionate about network and data security and has a certificate in Security Technology and Management from the Institute of Systems Science, National University of Singapore.

Books From Packt


ASP.NET 4 Social Networking
ASP.NET 4 Social Networking

jQuery 1.4 Reference Guide
jQuery 1.4 Reference Guide

ASP.NET Site Performance Secrets
ASP.NET Site Performance Secrets

jQuery 1.4 Animation Techniques: Beginners Guide
jQuery 1.4 Animation Techniques: Beginners Guide

ASP.NET MVC 2 Cookbook
ASP.NET MVC 2 Cookbook

Spring Roo 1.1 Cookbook
Spring Roo 1.1 Cookbook

JasperReports 3.6 Development Cookbook
JasperReports 3.6 Development Cookbook

Learning jQuery 1.3
Learning jQuery 1.3


Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software