New Bookstore! Save 20% on books with discount code: LAUNCH
Web Dev + WordPress + Security

New and Improved JavaScript Clock

Earlier this year, I posted an article explaining how to implement an unobtrusive JavaScript dynamic clock. While not completely earth-shattering or cutting-edge or anything like that, the dynamic JavaScript clock has received some great feedback from users who found the script to be exactly what they were looking for. In fact, a couple of weeks ago, Bill Brown went above and beyond by taking the time to improve the script with some great new features, including a “blinking seconds separator (for kicks)” and removal of “the need for the noscript tag.” Of course everything is yours to customize as desired. This quick post shares the complete script sent by Bill in a recent email (with slightly reformatted markup).

Demo

Unobtrusive JavaScript Clock

To build your own unobtrusive JavaScript clock, simply copy and paste the following code into a blank PHP document (no editing required!):

<!DOCTYPE>
<html>
	<head>
		<title>Demo: New and Improved JavaScript Clock - Perishable Press</title>
		<style type="text/css">
			.style {
				padding: 20px; font-family: monospace; font-weight: bold;
				border: 3px solid #c00; background-color: #f5f5e5;
				}
			.scripted .style {
				border: 3px double #ccc;
				}
		</style>
	</head>
	<body>
		
		<h1>New and Improved JavaScript Clock</h1>
		
		<div id="datetime" class="style">
			<span id="date"><?php echo date("l, F j, Y ~ "); ?></span> 
			<span id="time"><?php echo date("h:i:s A", time()); ?></span>
		</div>
		
		<script type="text/javascript">
			
			// Unobtrusive JavaScript Dynamic Clock
			// https://perishablepress.com/new-and-improved-javascript-clock/
			
			(function() { document.getElementsByTagName('html')[0].className='scripted' })();
			
			String.prototype.pad = function(l, s, t) {
				return s || (s = " "), (l -= this.length) > 0 ? 
				(s = new Array(Math.ceil(l / s.length) 
				+ 1).join(s)).substr(0, t = !t ? l : t == 1 ? 0 : Math.ceil(l / 2))
				+ this + s.substr(0, l - t) : this;
			};
			
			var addLoadEvent = function (func) {
				var oldonload = window.onload;
				if (typeof window.onload != 'function') {
					window.onload = func;
				} else {
					window.onload = function() {
						if (oldonload) {
							oldonload();
						}
						func();
					}
				}
			};
			
			var xClock = function () {
				var xC = null, xN = null, xH = null, xI = null,
				    xM = null, xS = null, xT = null, AP = null;
			
				if (!document.getElementById) return;
				xC = document.getElementById("time");
				if (!xC.nodeName) return;
				xN = new Date();
				xH = xN.getHours().toString().pad(2,'0',0);
				xM = xN.getMinutes().toString().pad(2,'0',0);
				xS = xN.getSeconds().toString().pad(2,'0',0);
				AP = (xH >= 12) ? "PM" : "AM";
				xH = (xH >= 13) ? (xH - 12) : xH;
				sS = (xN.getMilliseconds() >= 500) ? ":" : "&middot;";
				xT = xH + ":" + xM + sS + xS + " " + AP;
				xC.innerHTML = xT;
				xI = !xI ? null : clearTimeout(xI);
				xI = setTimeout(xClock, 500);
			};
			
			addLoadEvent(xClock);
			
		</script>
		
	</body>
</html>

This new version has a number of useful improvements, like adding a scripted class to the <html> tag, 12-hour time format, and more. Thanks again to Bill Brown for sharing this new and improved JavaScript clock.

Download

Here you may download the source files for this tutorial/demo:

Jeff Starr
About the Author
Jeff Starr = Creative thinker. Passionate about free and open Web.
Digging Into WordPress: Take your WordPress skills to the next level.

5 responses to “New and Improved JavaScript Clock”

  1. Hi.

    This is cool. So I can I replace the clock that comes with your Apathy theme with this clock? If that’s not possible, how do I add the “seconds” as you have on your site?

    Thank you!
    Chiwan

  2. Jeff Starr
    Jeff Starr 2009/01/06 6:26 pm

    Hi Chiwan, I got your email and have sent some information that may help you with this.

  3. What about appending in the current timezone to the output (such as EST or EDT)?

  4. The blinking does not work well on Mac Firefox or Safari.

    Only the seconds have the bottom dot blinking (the top dot for seconds does not blink. The minutes does do not blink at all.

  5. Jeff Starr
    Jeff Starr 2009/04/19 3:29 pm

    @Shefik: Sounds like a browser issue.. I am not sure how much control external JavaScript can provide over such minutia. Perhaps there is a way to resolve the issue with (X)HTML or CSS?

Comments are closed for this post. Something to add? Let me know.
Welcome
Perishable Press is operated by Jeff Starr, a professional web developer and book author with two decades of experience. Here you will find posts about web development, WordPress, security, and more »
Banhammer: Protect your WordPress site against threats.
Thoughts
LOL @ “weekly” support: “Your request has been received and will be reviewed soon. Neil (your support guy) checks support requests weekly. Rest assured we’ll get to it!” — Gotta be kidding with this.
After several days of work, finally taking a break. If anyone needs me, I'll be in Zora’s Domain, working thru Mah Eliya shrine.
Never ever call the client a useless idiot. Even if it’s true.
Inevitable that Google shuts down Feedburner. Maybe this year? Who knows. Here is a nice summary plus alternatives.
There is no way that Marvel can serve up anything better than what they've already done with Infinity saga/Endgame. Knowhere to go but down, sadly.
I built a new search launchpad to make my life easier. So I can search multiple engines quickly and easily.
Updating all muh plugins for WP 5.5 imminent release! Wut August :)
Newsletter
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.