HTML Goodies: Script Tip: Week 27

By Joe Burns


Another Tip of the Hat...

Does anybody really know what time it is?

Well, you do if you click the button below to see the clock run. This week we look at grabbing and altering the minute and second sections of the clock.

But first let's look at the script and its result one more time.



Here's the Code for the Clock

Man, that's a neat effect. Here's the code that grabs the minutes and seconds:


var min = RightNow.getMinutes()
if (min < 10)
{nmin = "0" +min}
else
{nmin = min}

var sec = RightNow.getSeconds()

if (sec < 10)
{nsec = "0" +sec}
else
{nsec = sec}

if (nsec >= 60)
{nnsec = "00"}
else
{nnsec = nsec}


We get the minute and second by calling for them through the use of RightNow.getMinutes() and RightNow.getSeconds(). Remember from Script Tip #26, we set up RightNow as the new Date(). We're using the two methods to extract the minutes and seconds.

The Minutes

Let's start with the minutes. The return is correct in terms of numbers, there's no need to add one to the return, but we do have to make one small change. And we, again, do it with an If statement.

Here's the deal. When the minute is less than 10, the return is a single digit. That doesn't look good. The user expects to see double digits no matter what the number. So, we set up the statement, that if the minute's return is less than 10, then add a zero in front and display. If the return is more than 10, do nothing. It looks like this:

if (min < 10)
{nmin = "0" +min}
else
{nmin = min}


Boom. We're done with the minutes. Let's do the seconds.

The Seconds

We'll do two things to the seconds. The first is exactly what we did with the minutes. If the second return is less than 10, add a zero in front and display.

The second alteration to the seconds return follows the same If statement format. However, this If statement will only come into play one time a minute.

One of the strangest things about the seconds return is that when the second "turns over" to count again, it always starts at 1. That means "60" is the highest number. Well, thatdoesn't look right. It should read "00", right? Yes! So, let's set up an If statement that checks the seconds for the number "60". If it finds "60" it will change it into "00" and display the double zero. The code looks like this:

if (nsec >= 60)
{nnsec = "00"}
else
{nnsec = nsec}

Hey! There ya go! Minutes and seconds! Now they look great and display well. It's starting to look like a clock.

Next Week: Setting A Time Out!


Learn to write your own JavaScripts with the
HTML Goodies 30-Step Primer Series
and take the knowledge home with you in
JavaScript Goodies!

You can find many other uses for JavaScript
on your Web pages here!


Make a Comment

Loading Comments...

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
  •  
  •  
  •  
Thanks for your registration, follow us on our social networks to keep up-to-date