Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Is there a way to display time ona webpage without a refresh? 2

Status
Not open for further replies.
Jul 13, 2001
180
US
Ihave used some vbscript to write the date and time. However, the time of course does not refresh and remains as it were when the user loads the page.

Having a meta-refresh works but what an eye-sore.

Any help would be greatly appreciated.

Thanks.
 
One simple method is to do something like:
Code:
<html>
<head>
  <script language=VBScript>
    Sub RefreshDateTime()
      divDateTime.innerText = FormatDateTime(Now(), vbGeneralDate)
    End Sub

    Sub window_onload()
      RefreshDateTime
      setInterval &quot;RefreshDateTime&quot;, 1000, &quot;VBScript&quot;
    End Sub
  </script>
</head>
<body>
  <div id=divDateTime
    style='font: bold 11px/11px &quot;Courier New&quot;; text-align: right'>
  </div>
  <div>
    This is an example of a page using client-side script
    to provide a running clock for the user.
  </div>
</body>
</html>
The overhead isn't as bad as it might appear.

Other alternatives include using an ActiveX control or a Java applet.
 
Client side script is better off in JavaScript, it will work on more browsers and devices (think for the future).
Adapted from dilettante's (had to make it DOM compliant too!), just paste into a new doc:
Code:
<!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot; &quot;[URL unfurl="true"]http://www.w3.org/TR/html4/loose.dtd&quot;>[/URL]
<html>
<head>
<title>testbed</title>
<style type=&quot;text/css&quot;>
#divDateTime {
	font: courier;
	color: blue;
}
</style>
<script language=&quot;JavaScript&quot; type=&quot;text/javascript&quot;>
var timeDiv //global var

function start() {
	//init reference to 'time' div
	timeDiv = document.getElementById(&quot;divDateTime&quot;);
	
	//start first time refresh
	setTimeout(&quot;RefreshDateTime()&quot;, 1)
}
function RefreshDateTime() {
	//put current time into timeDiv using DOM
	timeDiv.firstChild.nodeValue = (new Date()).toLocaleString();
	
	//now call this function again in one second
	setTimeout(&quot;RefreshDateTime()&quot;, 1000)
}

</script>
</head>
<body onload=&quot;start();&quot;>
  <p>Your computer time is now: <span id=&quot;divDateTime&quot;>0</span></p>
  <p>
    This example now works using accepted standards and would probably work on a PDA or mobile phone :).
  </p>
</body>
</html>

[spin2]

Posting code? Wrap it with code tags: [ignore]
Code:
[/ignore][code]CodeHere
[ignore][/code][/ignore].
 
Thank you, that was quite awesome as well!
May I ask? How would I strip off the seconds if I should desire and perhaps replace the colon between the hour and second with a blinking one to the beat of a second?
 
That was pretty interesting! Here's the result:
Code:
<!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot; &quot;[URL unfurl="true"]http://www.w3.org/TR/html4/loose.dtd&quot;>[/URL]
<html>
<head>
<title>testbed</title>
<style type=&quot;text/css&quot;>
#divClock {
	font-size: 16px;
	font-family: &quot;Courier New&quot;, monospace;
	color: #333333;
	background-color: #CCFFCC;
	border: 1px solid black;
	width: 55px; /*CSS experts: have this auto somehow? */
}
</style>
<script language=&quot;JavaScript&quot; type=&quot;text/javascript&quot;>
// global vars to point to clock spans
var hoursObj, sepObj, minsObj;
var rightNow, hours, mins, tmp;

function start() {
	//init references to clock spans
	hoursObj = document.getElementById(&quot;hoursID&quot;);
	sepObj = document.getElementById(&quot;sepID&quot;);
	minsObj = document.getElementById(&quot;minsID&quot;);
	
	//start first time refresh
	setTimeout(&quot;RefreshDateTime()&quot;, 1)
}
function RefreshDateTime() {
	//get current time and split into hours / mins
	rightNow = new Date();
	hours = rightNow.getHours();
	mins = rightNow.getMinutes();
	
	//update hours / mins spans
	hoursObj.firstChild.nodeValue = hours;
	minsObj.firstChild.nodeValue = mins;
	
	//toggle separator every second so it blinks
	toggleSeparator();
	
	//now call this function again in one second
	setTimeout(&quot;RefreshDateTime()&quot;, 1000)
}

function toggleSeparator() {
	//check current status
	tmp = sepObj.firstChild.nodeValue;
	
	//swap to opposite
	if (tmp == &quot;:&quot;)
		tmp = &quot; &quot;;
	else
		tmp = &quot;:&quot;;
		
	//update to new status
	sepObj.firstChild.nodeValue = tmp;
}
</script>
</head>
<body onload=&quot;start();&quot;>
  <div id=&quot;divClock&quot;><span id=&quot;hoursID&quot;>0</span><span id=&quot;sepID&quot;>:</span><span id=&quot;minsID&quot;>0</span></div>
  <p>V2.0: Digital Clock :)<br>
  This example now works using accepted standards and would probably work on a PDA or mobile phone :).</p>
</body>
</html>

Should probably post up in the javascript forum too, for interested parties.

Posting code? Wrap it with code tags: [ignore]
Code:
[/ignore][code]CodeHere
[ignore][/code][/ignore].
 
OMG. YOU totally rock!
Although I DO NOT WANT to sound like an ingrate in any sense, shape or form, because I am sincerely so graciously thankful, and also code challenged; how could just make that not military time, and just use AM or PM?

Sincere thanks.
And eveen if you can't assist further on this, I am extremely grateful.

Cheers!
 
Caution!

The comments below contain personal opinions you might just strongly disagree with. Take them with a grain of salt, and try to glean any value from them that they may have.


;-)

There is a disease common among those who write in languages descended from Object C (which includes Javascript). I call it &quot;drunk on objects.&quot;

The typical manifestation you see in DHTML is abuse of the DOM in order to code using deep object hierarchies. This is not only horribly inefficient, it leads to obsure code. Worse yet, attempts to correct for these inefficiencies by caching object references to things deep down in the multiply-nested object hierarchy makes the code even less readable.

You don't only end up with unnecessary globals and the need to write more globs of code to initialize them. No, worse than this you end up inventing a whole parallel set of names for things that already have been given perfectly good names in the DOM via the
Code:
id
property!

This insanity continues by using bizarre and dangerous constructs such as
Code:
objRef.firstChild.nodeValue
that spin the wheel of fortune hoping against hope that the particular browser in use just happened to implement a useful property such as
Code:
innerText
as the first child node in the object's properties collection. Nowhere is such a thing specified in the W3C's DOM definition documents.

As the W3C says:

Document Object Model (DOM) Level 1 Specification (Second Edition)
Version 1.0
W3C Working Draft 29 September, 2000


&quot;1.1.4. Inheritance vs. Flattened Views of the API

&quot;The DOM Core APIs present two somewhat different sets of interfaces to an XML/HTML document; one presenting an 'object oriented' approach with a hierarchy of inheritance, and a 'simplified' view that allows all manipulation to be done via the Node interface without requiring casts (in Java and other C-like languages) or query interface calls in COM environments. These operations are fairly expensive in Java and COM, and the DOM may be used in performance-critical environments, so we allow significant functionality using just the Node interface. Because many other users will find the inheritance hierarchy easier to understand than the 'everything is a Node' approach to the DOM, we also support the full higher-level interfaces for those who prefer a more object-oriented API.&quot;

DOM 2.0 says the same thing exactly.

You can see the &quot;drunk on objects&quot; disease even in the writings of the W3C, where they laughably claim deep object hierachies are easier to understand!!!

While object concepts are valuable things, just as with so much in life there is such as thing as too much of a good thing. &quot;Object orientation&quot; is a form of mental illness, and it wastes valuable resources and obscures code. But this is an old debate, and there is little to be accomplished now besides trying to educate people. It is sad there are so many bad books and worse examples out there floating around.

Nasty, nasty, ptui!

I was also amused by the statement that DHTML should be coded in Javascript to think for the future. This is highly amusing as well, since browsers that don't support VBScript are nearly extinct. Use of Javascript is clearly thinking in the past. But I cannot dispute the value of client-side Javascript in getting you that last 8% of die-hards who are still fighting the Microsoft juggernaut, and I salute you. That's about the only place I could be persuaded to use Javascript myself.

Something more productive

Ok, now that the ranting is (mostly) out of the way, here is how to code the thing so that it is still DOM-compliant (as was the VBScript example), but does not suffer from the excesses of &quot;drunk on objects.&quot;

Ironically, the comments have been deleted for clarity.
Code:
<html>
<head>
<title>testbed</title>
<style type=&quot;text/css&quot;>
#clockDiv {
    font-size: 16px;
    font-family: &quot;Courier New&quot;, monospace;
    color: #333333;
    background-color: #CCFFCC;
    border: 1px solid black;
    width: 75px
}
</style>
<script language=JavaScript>
function start() {
    refreshDateTime();
    setInterval(&quot;refreshDateTime()&quot;, 1000)
};

function refreshDateTime() {
    var rightNow = new Date();
    var hours = rightNow.getHours()
    
    hourSpan.innerText = (&quot; &quot; + ((hours + 11) % 12 + 1)).slice(-2);
    minSpan.innerText = (&quot;0&quot; + rightNow.getMinutes()).slice(-2);
    halfSpan.innerText = ((hours / 12).floor == 1) ? &quot;PM&quot; : &quot;AM&quot;;
    
    toggleSeparator()
};

function toggleSeparator() {
    if (sepSpan.innerText == &quot;:&quot;)
        sepSpan.innerText = &quot; &quot;
    else
        sepSpan.innerText = &quot;:&quot;
}
</script>
</head>
<body onload=&quot;Javascript: start()&quot;>
  <div id=clockDiv><span id=hourSpan></span><span id=sepSpan></span><span 

id=minSpan></span><span id=halfSpan></span></div>
  <p>V2.0+: Digital Clock <span style=&quot;font: normal 20pt Wingdings&quot;>C</span><br>
  This example eliminates several poor practices common in Javascript.</p>
</body>
</html>
You might want to replace the <!DOCTYPE> for those very few browsers that do not default to &quot;loose transitional.&quot; It doesn't hurt anything, but it adds no value here either.

See how much more compact and understandable this is?

No &quot;magic incantations&quot; like
Code:
objRef.firstChild.nodeValue
, all clear and explicit. The only ugly parts are the garish Javascript syntax required for arithmetic, string manipulation, and conditional expressions.

In conclusion

I hope this was informative and useful, and not too upsetting. If it doesn't discourage you entirely from writing Javascript in the future, perhaps it will provide you with the knowledge that you can write better Javascript. Better means shorter, clearer, and cleaner. No mumbo-jumbo, no flag waving claims about &quot;standards compliance&quot; (the W3C specifically says there is no scripting language specified in the DOM or in the HTML standards, all are equal, plus the so-called &quot;simplified&quot; view of the DOM is baked into the DOM's DNA).

And you know what? This is the VBScript forum!

Much of the above emotion comes from a deep frustration that Microsoft won the browser wars in 1997. Which doesn't matter much because they won the desktop wars by 1994. But these are both deeply disturbing events. I also do not recommend posting to forums well after midnight, as you can get (more than) a little crazy by then.
 
Dilettante, that was way way groovy!
Aces! Thanks again! :)

And I do prefer VBScript.
 
dilettante,

How would I change the font to verdana to match the date and time I have on a certain page. Now aside from the obvious, I went in and changed the font from courier to Verdana. This is where the little problem comes in, the colon in Verdana and a number of other fonts that I have tried does not have the same space as &quot;&quot;. So when it blinks, the minutes jump to the right and back.

The solution I thought of was to change the font color of the colon to black then white, so that it would seem to &quot;disappear&quot; since the page's BG color is also white.
In VBScript it would be simple to do, but I am lost trying every combination to change the color in <code>sepSpan.innerText = &quot;:&quot;</code> to white.
I did searches in google on how to change the color in a javascript function and all I got was either no display or the lovely javascript error when I applied it.

Your help would be greatly appreciated once again.

Thank you.
 
dilettante:

You are welcome to your opinion on objects and/or ignoring their use. I'll not go into that debate.

However: removing all the comments from an educational javascript function, and then claiming it is better - this is just plain ignorant.
1) if you actually work with scripts and need to modify or reuse something you created 6 months or 4 years ago, you will waste your own time if there are no comments.
2) the space you save is almost negligably small (800 bytes size difference between our two files)
Ironically, you think you have improved it by removing the comments.. I don't want to get into a kicking contest over this - just read up other people's considerable experience of the subject.

The second thing I want to refute is your notion that using a standardised scripting language (ECMAscript) is pointless because &quot;browsers that don't support VBscript are nearly extinct&quot;. See, this is how you are shooting yourself in the foot. The *only* browser that supports VBscript is Internet Explorer, currently available on the mac and windows only. It probably represents about 90% or more of the desktop browser market. So, if you go with an IE-only solution (like your one above), and you are happy with only reaching those people - fine. But you are definitely thinking only for the present. Ask 6 million Japanese people who use the internet from their phones if they will be able to see a VBscript function.
The desktop is becoming less and less the 'only' way onto the internet, and if you shoot yourself in the foot now you are only restricting your audience and giving yourself more work in the future.


Posting code? Wrap it with code tags: [ignore]
Code:
[/ignore][code]CodeHere
[ignore][/code][/ignore].
 
Hmm...

Fragment of last example, altered to flip the colon's
Code:
visibility
style:
Code:
function toggleSeparator() {
    if (sepSpan.
Code:
style.visibility == &quot;visible&quot;
Code:
)
        sepSpan.
Code:
style.visibility = &quot;hidden&quot;
Code:
    else
        sepSpan.
Code:
style.visibility = &quot;visible&quot;
Code:
}
</script>
</head>
<body onload=&quot;Javascript: start()&quot;>
  <div id=clockDiv><span id=hourSpan></span><span id=sepSpan>
Code:
:
Code:
</span><span id=minSpan></span><span id=halfSpan></span></div>
Note that the previous example didn't need the colon hard-coded as as the text of its <span> but this version does.

But for further advice on this topic you might want to check the Javascript Forum instead.
 
Awesome!! Thank you.
So much talent and kindness here.
I am sincerely grateful.

Regards.
 
Just for future reference, what would I hve to change in the code to obtain the date/time from the server instead of the client?

Thank you
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top