SIGN UP MEMBER LOGIN:    
ARTICLE

Clock's Using Javascript in Asp.Net

Posted by Krishna Garad Articles | .NET 4.5 January 03, 2012
In this artcile we will see how to create the clocks on our webpage with javascript.
Reader Level:
Download Files:
 

Introduction

In this article we will see how to create the clocks on our webpage with javascript. We can create the clocks on server side using some timer control and some update panel which time to time make a postback to server and this clock will show the server time. If we want to create the clock on client side then only the way is using javascript.

Background

While google search I found lot of examples to create the clock with javascript on client side out of that I'm giving here three examples which can be helpful to display the clock on client browser with not much effort. So we will see three clock one-by-one.

Simple Clock

This clock is very basic clock will look like bellow screenshot

simpleclock.bmp
 

For Creating this 24 hours format clock follow the step given bellow.

Step 1

Add New page to application and write the given script in head section of the page like bellow.

<head>
<
script language="JavaScript">
     var clockID = 0;

    function UpdateClock() {
        if (clockID) {
            clearTimeout(clockID);
            clockID = 0;
        }

        var tDate = new Date();

        if ((tDate.getSeconds()) <= 9) {
            document.theClock.theTime.value = ""
+ tDate.getHours() + ":"
+ tDate.getMinutes() + ":0"
+ tDate.getSeconds();
            document.title = "The time is: "
+ tDate.getHours() + ":"
+ tDate.getMinutes() + ":0"
+ tDate.getSeconds();
        } else if ((tDate.getMinutes()) <= 9) {
            document.theClock.theTime.value = ""
+ tDate.getHours() + ":0"
+ tDate.getMinutes() + ":"
+ tDate.getSeconds();
            document.title = "The time is: "
+ tDate.getHours() + ":0"
+ tDate.getMinutes() + ":"
+ tDate.getSeconds();
        } else if (((tDate.getSeconds()) <= 9) && ((tDate.getMinutes()) <= 9)) {
            document.theClock.theTime.value = ""
+ tDate.getHours() + ":0"
+ tDate.getMinutes() + ":0"
+ tDate.getSeconds();
            document.title = "The time is: "
+ tDate.getHours() + ":0"
+ tDate.getMinutes() + ":0"
+ tDate.getSeconds();
        } else {

            document.theClock.theTime.value = ""
+ tDate.getHours() + ":"
+ tDate.getMinutes() + ":"
+ tDate.getSeconds();
            document.title = "The time is: "
+ tDate.getHours() + ":"
+ tDate.getMinutes() + ":"
+ tDate.getSeconds();
        }

        clockID = setTimeout("UpdateClock()", 1000);
    }
    function StartClock() {
        clockID = setTimeout("UpdateClock()", 500);
    }

    function KillClock() {
        if (clockID) {
            clearTimeout(clockID);
            clockID = 0;
        }
    }

</script>
</
head>

Step 2

We have the script ready now we need to call the StartClock and StopClock function on body section like bellow.

<body onload="StartClock()" onunload="KillClock()">

Step 3

In Form now keep the control to display the time. We will keep the textbox input control of html to display the time.

<input name="theTime" size="8" type="text"/>

Clock With Images

This clock looks very effective clock because this clock uses it's GUI with images to display the time to client. This clock looks like bellow image.

imageclock.bmp
 

To create this clock follow the step given bellow.

Step 1

Add new page to your application copy the images uploaded with attachments and paste it in your root directory.

Step 2

In body section write the script given bellow. Initially we have to display the static images and then write the script.

<body>
    <form id="form1" runat="server">
    <div>
    <table>
    <tr>
<td bgcolor="black" height="45">
<img src="dg8.gif" name="hr1">
<img src="dg8.gif" name="hr2">
<img src="dgc.gif" name="c">
<img src="dg8.gif" name="mn1">
<img src="dg8.gif" name="mn2">
<img src="dgc.gif" name="c">
<img src="dg8.gif" name="se1">
<img src="dg8.gif" name="se2">
<img src="dgpm.gif" name="ampm">
</td></tr></table>

<script language="javascript"><!--    start

     dg0 = new Image(); dg0.src = "dg0.gif";
    dg1 = new Image(); dg1.src = "dg1.gif";
    dg2 = new Image(); dg2.src = "dg2.gif";
    dg3 = new Image(); dg3.src = "dg3.gif";
    dg4 = new Image(); dg4.src = "dg4.gif";
    dg5 = new Image(); dg5.src = "dg5.gif";
    dg6 = new Image(); dg6.src = "dg6.gif";
    dg7 = new Image(); dg7.src = "dg7.gif";
    dg8 = new Image(); dg8.src = "dg8.gif";
    dg9 = new Image(); dg9.src = "dg9.gif";
    dgam = new Image(); dgam.src = "dgam.gif";
    dgpm = new Image(); dgpm.src = "dgpm.gif";
    dgc = new Image(); dgc.src = "dgc.gif";

    function dotime() {
        theTime = setTimeout('dotime()', 1000);
        d = new Date();
        hr = d.getHours() + 100;
        mn = d.getMinutes() + 100;
        se = d.getSeconds() + 100;
        if (hr == 100) { hr = 112; am_pm = 'am'; }
        else if (hr < 112) { am_pm = 'am'; }
        else if (hr == 112) { am_pm = 'pm'; }
        else if (hr > 112) { am_pm = 'pm'; hr = (hr - 12); }
        tot = '' + hr + mn + se;
        document.hr1.src = 'dg' + tot.substring(1, 2) + '.gif';
        document.hr2.src = 'dg' + tot.substring(2, 3) + '.gif';
        document.mn1.src = 'dg' + tot.substring(4, 5) + '.gif';
        document.mn2.src = 'dg' + tot.substring(5, 6) + '.gif';
        document.se1.src = 'dg' + tot.substring(7, 8) + '.gif';
        document.se2.src = 'dg' + tot.substring(8, 9) + '.gif';
        document.ampm.src = 'dg' + am_pm + '.gif';
    }
    dotime();
//end -->
</script>

    </div>
    </form>
    <p>
        <strong>Clock Created Using Images</strong></p>
</body>

Movable Clock

This clock is most attractive and animated clock along above two clocks. This Clock will appear only in IE in other browser it will not support. This cloc will look like bellow.

movable.bmp
 

To create this clock follow the the step given.

Step 1:

Add new form and by default our form have some lines written like bellow.

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

Here it's specifying the XHTML 1.0 but we have to modify this to HTML 4.0

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

Step 2

Write the following script in body element.

<body>
<
script language="JavaScript" type="text/javascript"><!--

    dCol = 'Red'; //date colour.
    fCol = 'Green'; //face colour.
    sCol = 'Black'; //seconds colour.
    mCol = 'Blue'; //minutes colour.
    hCol = '000000'; //hours colour.
    ClockHeight = 40;
    ClockWidth = 40;
    ClockFromMouseY = 0;
    ClockFromMouseX = 100;

    //Alter nothing below! Alignments will be lost!

    d = new Array("SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY");
    m = new Array("JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER");
    date = new Date();
    day = date.getDate();
    year = date.getYear();
    if (year < 2000) year = year + 1900;
    TodaysDate = " " + d[date.getDay()] + " " + day + " " + m[date.getMonth()] + " " + year;
    D = TodaysDate.split('');
    H = '...';
    H = H.split('');
    M = '....';
    M = M.split('');
    S = '.....';
    S = S.split('');
    Face = '1 2 3 4 5 6 7 8 9 10 11 12';
    font = 'Arial';
    size = 1;
    speed = 0.5;
    ns = (document.layers);
    ie = (document.all);
    Face = Face.split(' ');
    n = Face.length;
    a = size * 10;
    ymouse = 0;
    xmouse = 0;
    scrll = 0;
    props = "<font face=" + font + " size=" + size + " color=" + fCol + "><B>";
    props2 = "<font face=" + font + " size=" + size + " color=" + dCol + "><B>";
    Split = 360 / n;
    Dsplit = 360 / D.length;
    HandHeight = ClockHeight / 4.5
    HandWidth = ClockWidth / 4.5
    HandY = -7;
    HandX = -2.5;
    scrll = 0;
    step = 0.06;
    currStep = 0;
    y = new Array(); x = new Array(); Y = new Array(); X = new Array();
    for (i = 0; i < n; i++) { y[i] = 0; x[i] = 0; Y[i] = 0; X[i] = 0 }
    Dy = new Array(); Dx = new Array(); DY = new Array(); DX = new Array();
    for (i = 0; i < D.length; i++) { Dy[i] = 0; Dx[i] = 0; DY[i] = 0; DX[i] = 0 }
    if (ns) {
        for (i = 0; i < D.length; i++)
            document.write('<layer name="nsDate' + i + '" top=0 left=0 height=' + a + ' width=' + a + '><center>' + props2 + D[i] + '</font></center></layer>');
        for (i = 0; i < n; i++)
            document.write('<layer name="nsFace' + i + '" top=0 left=0 height=' + a + ' width=' + a + '><center>' + props + Face[i] + '</font></center></layer>');
        for (i = 0; i < S.length; i++)
            document.write('<layer name=nsSeconds' + i + ' top=0 left=0 width=15 height=15><font face=Arial size=3 color=' + sCol + '><center><b>' + S[i] + '</b></center></font></layer>');
        for (i = 0; i < M.length; i++)
            document.write('<layer name=nsMinutes' + i + ' top=0 left=0 width=15 height=15><font face=Arial size=3 color=' + mCol + '><center><b>' + M[i] + '</b></center></font></layer>');
        for (i = 0; i < H.length; i++)
            document.write('<layer name=nsHours' + i + ' top=0 left=0 width=15 height=15><font face=Arial size=3 color=' + hCol + '><center><b>' + H[i] + '</b></center></font></layer>');
    }
    if (ie) {
        document.write('<div id="Od" style="position:absolute;top:0px;left:0px"><div style="position:relative">');
        for (i = 0; i < D.length; i++)
 
         
document.write('<div id="ieDate" style="position:absolute;top:0px;left:0;height:' + a + ';width:' + a + ';text-align:center">' + props2 + D[i] +'</B></font></div>');
        document.write('</div></div>');
        document.write('<div id="Of" style="position:absolute;top:0px;left:0px"><div style="position:relative">');
        for (i = 0; i < n; i++)
            document.write('<div id="ieFace" style="position:absolute;top:0px;left:0;height:' + a + ';width:' + a + ';text-align:center">' + props + Face[i] + '</B></font></div>');
        document.write('</div></div>');
        document.write('<div id="Oh" style="position:absolute;top:0px;left:0px"><div style="position:relative">');
        for (i = 0; i < H.length; i++)
            document.write('<div id="ieHours" style="position:absolute;width:16px;height:16px;font-family:Arial;font-size:16px;color:' + hCol + ';text-align:center;font-weight:bold">' + H[i] + '</div>');
        document.write('</div></div>');
        document.write('<div id="Om" style="position:absolute;top:0px;left:0px"><div style="position:relative">');
        for (i = 0; i < M.length; i++)
            document.write('<div id="ieMinutes" style="position:absolute;width:16px;height:16px;font-family:Arial;font-size:16px;color:' + mCol + ';text-align:center;font-weight:bold">' + M[i] + '</div>');
        document.write('</div></div>')
        document.write('<div id="Os" style="position:absolute;top:0px;left:0px"><div style="position:relative">');
        for (i = 0; i < S.length; i++)
            document.write('<div id="ieSeconds" style="position:absolute;width:16px;height:16px;font-family:Arial;font-size:16px;color:' + sCol + ';text-align:center;font-weight:bold">' + S[i] + '</div>');
        document.write('</div></div>')
    }
    (ns) ? window.captureEvents(Event.MOUSEMOVE) : 0;
    function Mouse(evnt) {
        ymouse = (ns) ? evnt.pageY + ClockFromMouseY - (window.pageYOffset) : event.y + ClockFromMouseY;
        xmouse = (ns) ? evnt.pageX + ClockFromMouseX : event.x + ClockFromMouseX;
    }
    (ns) ? window.onMouseMove = Mouse : document.onmousemove = Mouse;
    function ClockAndAssign() {
        time = new Date();
        secs = time.getSeconds();
        sec = -1.57 + Math.PI * secs / 30;
        mins = time.getMinutes();
        min = -1.57 + Math.PI * mins / 30;
        hr = time.getHours();
        hrs = -1.575 + Math.PI * hr / 6 + Math.PI * parseInt(time.getMinutes()) / 360;
        if (ie) {
            Od.style.top = window.document.body.scrollTop;
            Of.style.top = window.document.body.scrollTop;
            Oh.style.top = window.document.body.scrollTop;
            Om.style.top = window.document.body.scrollTop;
            Os.style.top = window.document.body.scrollTop;
        }
        for (i = 0; i < n; i++) {
            var F = (ns) ? document.layers['nsFace' + i] : ieFace[i].style;
            F.top = y[i] + ClockHeight * Math.sin(-1.0471 + i * Split * Math.PI / 180) + scrll;
            F.left = x[i] + ClockWidth * Math.cos(-1.0471 + i * Split * Math.PI / 180);
        }
        for (i = 0; i < H.length; i++) {
            var HL = (ns) ? document.layers['nsHours' + i] : ieHours[i].style;
            HL.top = y[i] + HandY + (i * HandHeight) * Math.sin(hrs) + scrll;
            HL.left = x[i] + HandX + (i * HandWidth) * Math.cos(hrs);
        }
        for (i = 0; i < M.length; i++) {
            var ML = (ns) ? document.layers['nsMinutes' + i] : ieMinutes[i].style;
            ML.top = y[i] + HandY + (i * HandHeight) * Math.sin(min) + scrll;
            ML.left = x[i] + HandX + (i * HandWidth) * Math.cos(min);
        }
        for (i = 0; i < S.length; i++) {
            var SL = (ns) ? document.layers['nsSeconds' + i] : ieSeconds[i].style;
            SL.top = y[i] + HandY + (i * HandHeight) * Math.sin(sec) + scrll;
            SL.left = x[i] + HandX + (i * HandWidth) * Math.cos(sec);
        }
        for (i = 0; i < D.length; i++) {
            var DL = (ns) ? document.layers['nsDate' + i] : ieDate[i].style;
            DL.top = Dy[i] + ClockHeight * 1.5 * Math.sin(currStep + i * Dsplit * Math.PI / 180) + scrll;
            DL.left = Dx[i] + ClockWidth * 1.5 * Math.cos(currStep + i * Dsplit * Math.PI / 180);
        }
        currStep -= step;
    }
    function Delay() {
        scrll = (ns) ? window.pageYOffset : 0;
        Dy[0] = Math.round(DY[0] += ((ymouse) - DY[0]) * speed);
        Dx[0] = Math.round(DX[0] += ((xmouse) - DX[0]) * speed);
        for (i = 1; i < D.length; i++) {
            Dy[i] = Math.round(DY[i] += (Dy[i - 1] - DY[i]) * speed);
            Dx[i] = Math.round(DX[i] += (Dx[i - 1] - DX[i]) * speed);
        }
        y[0] = Math.round(Y[0] += ((ymouse) - Y[0]) * speed);
        x[0] = Math.round(X[0] += ((xmouse) - X[0]) * speed);
        for (i = 1; i < n; i++) {
            y[i] = Math.round(Y[i] += (y[i - 1] - Y[i]) * speed);
            x[i] = Math.round(X[i] += (x[i - 1] - X[i]) * speed);
        }
        ClockAndAssign();
        setTimeout('Delay()', 40);
    }
    if (ns || ie) window.onload = Delay;
// --></script>

    <p>
        <strong>Animated Clock:</strong></p>
    <p>
        <strong>Move the mouse and see what happens.</strong></p>

</body>

Run the application in IE only and see the effect of this movable clock.

Conclusion

Using simple javascript only we can create the various clocks without any extra efforts.

Login to add your contents and source code to this article
share this article :
post comment
 

thank's all guys hearing good feedback from you.

Posted by Krishna Garad Jan 05, 2012

Great job. Good article.

Posted by Abhi Kumar Jan 04, 2012

Very nicely presented.

Posted by Monika Arora Jan 04, 2012

thanks mr. But i face error when i want to load or execute the page. the error is " Unable to get value of the property 'theTime': object is null or undefined " help me please.

Posted by mohammad nabhan Jan 04, 2012
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Become a Sponsor