3D Transform using CSS3 and jQuery Animation

In this article, we will see how to use CSS3 3D transform with jQuery animate method. To start with, CSS3 supports some new features like –

1. CSS3 Selectors.
2. Rounded Corners.
3. Background Decoration.
4. Colors – [Linear Gradients/Radial Gradients].
5. Text Effects.
6. 2D and 3D Transforms.
7. Animations and many more.

Out of these features, in this article, we will look at 3D transform with jQuery animation. Let’s start by creating an empty web application using Visual Studio with the name “QuarterSalesDetails”. For this demonstration, I am using Visual Studio 2013 although you can use a previous edition of Visual Studio too.

Once you click on the OK button, you will see a New ASP.NET Project dialog box where you can choose your own web template based on your develop environment and requirements in your organization. The dialog box is shown below. Please make a choice of Web Forms for this demonstration.

image

Once your project is ready, let’s first reference jQuery in our project using the Nuget package. Right click the project and click on “Manage NuGet Packages” as shown below –

nuget

Install jQuery. This will create a Scripts folder in your project and add the needed jQuery files. Once you are done with the jQuery installation, we will now add a HTML page in our project with the name “QuarterSales”.

Drag and drop the jQuery file from the scripts folder into our <Head> tag. Your page should look like below –

html1

Now let’s add the following code in our HTML <body> -

<div class="divFlip3D">
<div class="front">
    <h1>Quarter wise Sales for Last 4 Year</h1>
    <table border="1" style="background-color:lightyellow;margin:5px;">
        <thead>
            <tr>
                <th>
                    Year
                </th>
                <th>
                    Quarters
                </th>
                <th>
                    Choose Quarter
                </th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td class="year">2003</td>
                <td class="Q">Q1</td>
                <td class="Select"><a href="#">Choose Quarter</a></td>
            </tr>
            <tr>
                <td class="year">2003</td>
                <td class="Q">Q2</td>
                <td class="Select"><a href="#">Choose Quarter</a></td>
            </tr>
            <tr>
                <td class="year">2003</td>
                <td class="Q">Q3</td>
                <td class="Select"><a href="#">Choose Quarter</a></td>
            </tr>
            <tr>
                <td class="year">2003</td>
                <td class="Q">Q4</td>
                <td class="Select"><a href="#">Choose Quarter</a></td>
            </tr>
        </tbody>
    </table>
</div>
<div class="back" style="text-align:center;">
    <h1>Total Sales In this Quarter</h1>
    <table id="salesDetailsTable" border="1" style="background-color:lightyellow;margin:10px;">
        <tr>
            <th>Year</th>
            <th>Month</th>
            <th>Total Sales</th>
        </tr>
    </table>
</div>
</div>


Now we will apply a style to our HTML content. Add the following code in our <head> tag, although ideally you should keep all CSS and Scripts in separate files –

<style>
h1 {
    color: #fff;
}

.divFlip3D {
    width: 350px;
    margin: 10px;
    float: left;
}

    .divFlip3D > .front {
        position: absolute;
        transform: perspective(600px) rotateY(0deg);
        background: #0094ff;
        width: 350px;
        height: 350px;
        border-radius: 10px;
        backface-visibility: hidden;
        -moz-transition: transform .5s linear 0s;
        -o-transition: transform .5s linear 0s;
        -webkit-transition: transform .5s linear 0s;
        transition: transform .5s linear 0s;
    }

    .divFlip3D > .back {
        position: absolute;
        transform: perspective(600px) rotateY(180deg);
        background: #0094ff;
        width: 350px;
        height: 350px;
        border-radius: 10px;
        backface-visibility: hidden;
        -moz-transition: transform .5s linear 0s;
        -o-transition: transform .5s linear 0s;
        -webkit-transition: transform .5s linear 0s;
        transition: transform .5s linear 0s;
    }
</style>


In the above CSS, we are using CSS3 Transform with perspective set to 600 pixel and rotate Y to 0 and 180 degree to back and front CSS class. We are also using border radius and transition of CSS3.

Now we need a web service which will return the three months sales for a given quarter. For writing a web service, we will first add a C# class in our project and write code as shown below –

public class QuarterSalesClass
{
    public decimal MonthlySales { get; set; }
    public string MonthName { get; set; }
    public int Year { get; set; }
}


Once your class is ready, add a web service to your project and add the following code in your web service –

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class QuarterSalesService : System.Web.Services.WebService
{

    [WebMethod]
    public List<QuarterSalesClass> GetQuarterSales(string quarter)
    {
        List<QuarterSalesClass> salesData = new List<QuarterSalesClass>();
        if (quarter=="Q1")
        {
            salesData.Add(new QuarterSalesClass() { MonthName="Jan", MonthlySales=1200000,Year=DateTime.Now.Year });
            salesData.Add(new QuarterSalesClass() { MonthName = "Feb", MonthlySales = 4200000, Year = DateTime.Now.Year });
            salesData.Add(new QuarterSalesClass() { MonthName = "Mar", MonthlySales = 7200000, Year = DateTime.Now.Year });
        }
        else if(quarter=="Q2")
        {
            salesData.Add(new QuarterSalesClass() { MonthName = "Apr", MonthlySales = 2200000, Year = DateTime.Now.Year });
            salesData.Add(new QuarterSalesClass() { MonthName = "May", MonthlySales = 6200000, Year = DateTime.Now.Year });
            salesData.Add(new QuarterSalesClass() { MonthName = "Jun", MonthlySales = 5200000, Year = DateTime.Now.Year });
        }
        else if (quarter == "Q3")
        {
            salesData.Add(new QuarterSalesClass() { MonthName = "Jul", MonthlySales = 1300000, Year = DateTime.Now.Year });
            salesData.Add(new QuarterSalesClass() { MonthName = "Aug", MonthlySales = 3400000, Year = DateTime.Now.Year });
            salesData.Add(new QuarterSalesClass() { MonthName = "Sept", MonthlySales = 2200000, Year = DateTime.Now.Year });
        }
        else if (quarter == "Q4")
        {
            salesData.Add(new QuarterSalesClass() { MonthName = "Oct", MonthlySales = 1200000, Year = DateTime.Now.Year });
            salesData.Add(new QuarterSalesClass() { MonthName = "Nov", MonthlySales = 2200000, Year = DateTime.Now.Year });
            salesData.Add(new QuarterSalesClass() { MonthName = "Dec", MonthlySales = 3200000, Year = DateTime.Now.Year });
        }
        return salesData;
    }
}


In the above web service, the web method GetQuarterSales takes a string parameter quarter and returns the collection of QuarterSalesClass with the year, monthname and monthsales.

We will be using this web service method to fetch the quarter sales details using jQuery AJAX as per the user’s quarter selection.

Now let’s use the jQuery animate method which will flip the <div> tag on the click event of anchor. On the click event of anchor, we will call a web service method using jQuery AJAX by passing the required quarter. Write down the following jQuery code before the body tag ends. You can even write it in the <head> section, except that you will have to add it in $(function({});

<script>
$(function () {
$('.Select').click(function () {
    var details;
    var row = $(this).closest('tr');
    row.each(function () {
        details = {
            year: $(this).find('.year').html(),
            q1: $(this).find('.Q').html()
        };

        $({ r: 0 }).animate(
        {
            r: -180
        },
        {
            duration: 3000,
            step: function (now, fx) {
                $('.divFlip3D>.front').css('transform', 'perspective(600px) rotateY(' + now + 'deg)');

            }
        });
        $({ r: 180 }).animate(
        {
            r: 0
        },
        {
            duration: 3000,
            step: function (now, fx) {
                $('.divFlip3D>.back').css('transform', 'perspective(600px) rotateY(' + now + 'deg)');
            }
        });
        $.ajax({
            type: "POST",
            url: "QuarterSalesService.asmx/GetQuarterSales",
            data: "{quarter:\"" + details.q1 + "\"}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                var sales = msg.d;
                if (sales.length > 0) {
                    var sumOfSales;
                    for (var key in sales) {
                        var tr = '<tr><td>' + sales[key].Year + '</td><td>' + sales[key].MonthName + '</td><td>' + sales[key].MonthlySales + '</td></tr>';
                        $('#salesDetailsTable').append(tr);
                    }
                }
                else {
                    alert("No records found");
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
        });
    });

});
});
</script>


Now run your HTML page and click on the anchor hyperlink to choose the quarter you want to see the total sales for each month. Your final output should look like below

css-jquery

When animation starts, your output will change to the following –

css-3d-transform

In our jQuery code, we are selecting the table row. Then from the row, we are finding the value of the cell which contains the Quarter detail using a CSS class selector ‘Q’. After this, we are using an animate method of the jQuery to flip the div tags. Then we are calling a Web Service Method using $.ajax() method of jQuery. In the ajax() method, we are passing the quarter parameter value and fetching the details of the three months sales of that quarter.

And that’s it. We have seen how to use CSS3 3D transform with jQuery animate method.





2 comments:

CoolCraftsByCarolyn said...
This comment has been removed by the author.
CoolCraftsByCarolyn said...

Really great job! Thanks for posting!