Creating Simple Animating Object Using JavaScript in ASP.NET

In this example, we are going to learn how to animate an object using JavaScript. The object I'm referring to here is any image. Consider an example whereby we have an image and on click of that image the image should move from one place to another place. This task can be done using JavaScript in ASP.Net whereby we are moving an object from one place to another place.

The following is the design of the application.

Design

Whereby we have a div control which has an image being applied on the background and simultaneously inside the div we are having an image control displaying the image of an airplane when a user clicks on the airplane then that object will move from one place to another place.

The following is the source code for that.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript">
        var timer;

        function AnimateAero() {
            clearInterval(timer);
            document.getElementById("aero").style.left = "860px";
            timer = setInterval("TakeOff()", 10);
        }

        function TakeOff() {
            document.getElementById("aero").style.pixelLeft -= 2;
            if (document.getElementById("aero").style.pixelLeft < 0) {
                document.getElementById("aero").style.left = "860px";
                TakeOff();
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div style="position:relative; width:950px; height:350px; border:dashed 1px; background-image:url('clods.jpg'); background-repeat:inherit;" align="right">
            <img id="aero" src="aeroplane.jpg" style="position:absolute; left:846px; width:100px; top:126px; height:61px;" onclick="AnimateAero()" />
        </div>
    </form>
</body>
</html>

Animation

Hope that you'll like this example. In case of any queries please post them.


Similar Articles