Jump to content

[SOLVED] Js basics question


blackcell

Recommended Posts

<script type="text/javascript">
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
t=setTimeout('startTime()',500);
}

function checkTime(i)
{
if (i<10)
 {
 i="0" + i;
 }
return i;
}
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>

source: http://www.w3schools.com/js/tryit.asp?filename=tryjs_timing_clock

 

First, I am very new to javascript. I want to get to know js as well as php (where I don't have to grab examples from free script sites)

I have a few questions on how JS works.

 

First, how does the clock update automatically with every second?

Second, how does the <div> tag work?  Say if I wanted to insert the clock in a table, would I have to have the:

<div id="txt"></div>

like this:

...

<td><div id="txt"></div></td>

...

Link to comment
Share on other sites

 

The script gets the initial day and time from your computer. Then it uses setTimeout to create a timing event that update the text in your div every 1/2 a second. The DIV tag does not matter; as long as whatever element you want to display the time in; has an id of txt and the element is capable of displaying content in it; then you could use any element.

 

you could just do something like this:

 

<script type="text/javascript">
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
t=setTimeout('startTime()',500);
}

function checkTime(i)
{
if (i<10)
  {
  i="0" + i;
  }
return i;
}
</script>
</head>
<body onload="startTime()">
<table>
<tr>
<td id="txt"></td>
</tr>
</table>

 

or if you don't want to take up any space at all in your page; I suggest using a span, like so:

 

<span id="txt"></span>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.