Saturday, April 14, 2012

jQuery with ASP.NET III - Animations

Since jQuery has emerged, interactive and more responsive web applications become easier to develop in today's world. It provides many powerful features that you could get use very efficiently with less coding, which otherwise requires more development efforts and lines of code to accomplish a single effect. In this article we will focus on animation features provided by jQuery and use animation effect in our ASP.Net website.

Background

In last post jQuery in ASP.Net II - GridView, we explored some responsive behavior with GridView control and validate our multi-line textbox to specified limit of characters. Here we set our focus on different animation methods provided:
  • Enlarging text on mousehover
  • Creating fade effect on mousehover
  • Sliding elements
  • Animating the panel
  • Hide and Display panels
  • Chain of animations
Note that we only discuss code segments here for jQuery, with assumptions that corresponding ASP.Net controls are already placed on the webpage. You will get cleared while we proceed further. We will only discuss the code placed inside the script segment required for jQuery, like:
<script type="text/javascript">
     $(document).ready(function () {
         
         // our jQuery code will goes here...

     });
    </script>

Enlarging text on mousehover

We place a label with some text displayed in it, and on mousehover we will enalrged the text inside the label by changing its font size.
var origFontSize = parseFloat($(".enlarge").css('font-size'));
    $("#content").hover(
        function () {
            $(".enlarge").css("cursor", "pointer");
            var newFontSize = origFontSize * 3;
            $(".enlarge").animate({ fontSize: newFontSize }, 300);
        },
        function () {
            $(".enlarge").animate({ fontSize: origFontSize }, 300);                    
        }
    );
Assumption : You have placed a fieldset with ID = content and dropped a Label with CssClass = enlarge, and put come text content int it. We have defined the enlarge class as :
.enlarge
    {
        font-size: 12px;
        font-family: Arial,sans-serif;
    }
  • parseFloat($(".enlarge").css('font-size')) selects our label which
    has css class enlarge, and retrieve its font-size property, parseFloat to our variable origFontSize.
  • $("#content").hover set the hover event for our fieldset with id=content
  • Within the hover event, inside the mouseover function we set the cursor for our label control to pointer
  • newFontSize set our font size variable with new size, by multiplying original font size with our multiplier scale, 3 in this case.
  • $(".enlarge").animate({ fontSize: newFontSize }, 300); here the actual method comes which do the animation on our label control. animate method takes the animation object with properties required to animate. In our case we only passed the property fontSize with our new size value newFontSize. This directs the animate method to change the properties passed as parameters with new values. And the second parameter for animate method, we passed the time span value in milliseconds. In our case it takes 300 milliseconds to changes its font-size with new value.
  • $(".enlarge").animate({ fontSize: origFontSize }, 300); Inside the
    mouseout function, we reset our fontSize with original value contained in the variable origFontSize

Creating fade effect on mousehover

Place a fieldset with id = content and put an image control inside fieldset container.
$("#content").hover(
            function () {
                $("#<%=Image1.ClientID%>").css("cursor", "pointer");
                $("#<%=Image1.ClientID%>").fadeOut(1000);
            },
            function () {
                $("#<%=Image1.ClientID%>").fadeIn(1000);
            }
        );
Assumption : You have placed a fieldset with id = content, and have an image control inside the fieldset container with ID = Image1. Set its src property to an image's path, here we create an images folder at the website's root and put our image.jpg in this folder. Also set CssClass for our image control to imagecontent, which we defined as :
.imagecontent
        {
            width: 350px;
            height: 250px;
        }
  • $("#content").hover set the hover event for our fieldset with id=content
  • Within the hover event, inside the mouseover function we set the cursor for our image control to pointer
  • fadeOut is the actual method with creates the animation effect of fadeout. It takes the parameter to set the time span consumed to create the desired effect.
  • fadeIn Inside the mouseout function, we reset our image control with fadeIn with the required time span parameter.

Sliding elements

Drop a button control to provide the user a way to click and get slide the elements. Place a div with our any html content.
$("#<%= btnSubmit.ClientID%>").click(function (e) {
            e.preventDefault();
            if ($(".slide").is(":hidden")) {
                $(".slide").slideDown("slow");
            }
            else {
                $(".slide").slideUp("slow");
            }
        });
Assumption : You have placed a Button control on the form with ID = btnSubmit. And have a div with css class code>slide, we defined as :
.slide
        {
            font-size: 12px;
            font-family: Arial,sans-serif;
            display: none;
            height: 100px;
            background-color: #148A21;
            color:#000000;
        }
  • Attach click event for button btnSubmit.
  • e.preventDefault() stops the page from being postback, by preventing the default behavior.
  • $(".slide").is(":hidden") first check, if our element with css class slide is already hidden, if so, then slideDown("slow") our element. We have passed the constant timespan slow defined with jQuery, you could also change to any desired timespan value.
  • if our element is not already hidden, then we will slideUp our element with the constant timespane value slow.

Animating the panel

Drop a button control to let the user do animate the panel accordingly. Place a panel with our html content.
var regular = true;
        $("#<%=btnSubmit.ClientID%>").click(function (e) {
            e.preventDefault();

            if (regular == true) {
                $(".contentArea").animate({
                    opacity: 0.5,
                    width: "500px",
                    height: "280px",
                    fontSize: "36px",
                    borderWidth: "15px"
                }, "slow");
            }
            else {
                $(".contentArea").animate({
                    opacity: 1.0,
                    width: "300px",
                    height: "100px",
                    fontSize: "12px",
                    borderWidth: "5px"
                }, "slow");
            }

            regular = !regular;
        });
Assumption : You have dropped a button control on the form with ID = btnSubmit. Placed a panel with CssClass = contentArea, we have defined as :
.contentArea
        {
            font-size: 12px;
            font-family: Arial,sans-serif;
            width: 300px;
            height: 100px;
            background-color: #9999FF;
            border: solid;
        }
  • var regular = true define our variable to maintain the status for our panel animation.
  • Attach the click event for button btnSumbit.
  • e.preventDefault() stops the page from being postback, by preventing the default behavior.
  • regular == true first check, if we have not already applied our animation on the panel. then (".contentArea").animate() method is called with different values for different css properties we have to change or applied on our panel content, and second paramter (slow)for animate method is the timespan to consumed in the animation effect.
  • else if have already applied the animation effects, now we are reverting back to
    our original css properties for the panel. We have set our orinial values for different css properties to be set for the targeted panel.

Hide and Display panels

Lets hide and display different panels, a menu like panel headers displayed on the
web page and we explore the corresponding content panels when we clicked on any
header panel.
$(".content_head").click(function () {
            $(".content_body").hide(100);
            $(this).next(".content_body").slideToggle("slow");
        });
Assumption : You have placed a series of pairs of panels. Set CssClass = content_head for first panel, which act as menu header, and set CssClass = content_body for second panel which displays the content for that menu item. We defined these css classes as :
.content_head
    {
        width: 150px;
        height: 30px;
        background-color: #CCCCCC;
        cursor: pointer;
    }
    .content_body
    {
        display: none;
        width: 150px;
        height: 50px;
        background-color: #9999FF;
    }
  • Attach the click event for the panels with css class content_head.
  • $(".content_body").hide(100) first hide all the content elements, if already explored some other menu item and showing the content, we first hide that contents.
  • $(this).next(".content_body").slideToggle("slow") now grab the current clicked element by this and find the next content item attached for this menu item by next(".content_body"). Here we reached the content panel attached to the click menu item. Now we toggle the slide status by calling slideToggle() with constant timepspan slow.

Chain of animations

Now we place a panel box on the web page and animate it. We are not restricted to
animate our elements only once but jQuery provides the the power to chain your animation effects for any elements you want.
$("#<%=btnSubmit.ClientID%>").click(function (e) {
        e.preventDefault();
        $('.contentArea').animate({ left: "+=200"}, 2000)
                .animate({ top: "+=100"}, 700)
                .animate({ left: "-=400"}, 1200)
                .animate({ top: "-=100"}, 700)
                .animate({ left: "+=200"}, 2000);
        });
Assumption : You have dropped a button control with ID = btnSubmit
and let the user to control the animation effect by this button. Place a panel with
CssClass = contentArea, we have defined the css class as :
.contentArea
    {
        width: 50px;
        height: 50px;
        background-color: #71B3A2;
        border: solid;
        position: relative;
    }
    
  • Attach the click event for button btnSumbit.
  • e.preventDefault() stops the page from being postback, by preventing the default behavior.
  • $('.contentArea') select our panel and call animate()
    methods repetitively in a chain model. Keep min minde that the animate() methods returns object element to which it is already called, so by repetitively calling this method with continous . notation we actually calling this method for the same object in reptition pattern, because the method returns the same object to which it is called with updated object status.
  • animate({ left: "+=200"}, 2000)animates the panel by changing its position on the webpage, set its css left property to some new value, and provide the timespan 200 in milliseconds to complete the animation in this span.
  • animate({ top: "+=100"}, 700) changes the top position of the panel
    by adding some new value to its css property top.
  • animate({ left: "-=400"}, 1200) again change the left
    css property, but this time passes a negative value, so this value is now subtracted
    form the current left position of the panel on the webpage.
  • animate({ top: "-=100"}, 700) change the top css property, but this time passes a negative value, so this value is now subtracted form the current top position of the panel.
  • .animate({ left: "+=200"}, 2000); again change the left css property, and add change the left position of the panel.

References

ASP.Net jQuery Cookbook by Sonal Aneel Allana

We have explored some jQuery functions for achieving animation effects. jQuery offers many useful utilities to design animation, thus empowering developers to build rich animated pages for a better interactive experience for the web users. You must explore those methods and you will find that its now become very easy to develop interactive web pages with jQuery by spending very little effort.

You could download the working copy for these code samples from my CodeProject post
jQuery with ASP.NET III - Animations

1 comment:

  1. Very interesant
    Look at this blog, you will find many interesting things
    www.systemdeveloper.info

    ReplyDelete