Build a Browser Clock with JavaScript: jQuery Demo
By George Nicolaou
This WebSquadron recording demonstrates a clock built from two HTML elements. The original code is retained below as an example to study, not as a dependency you must install on a current WordPress site.
Know which time you are showing
new Date() uses the visitor’s environment. Putting “PARIS” beside the result does not turn it into Paris time. A clock for a named city needs an explicit time zone, for example when formatting with Intl.DateTimeFormat. Check daylight-saving changes as well as the displayed hour.
Review the older implementation
A current WordPress project should not load a second, older jQuery library solely for this example. Use the dependency already managed by the site, or write the small update function in plain JavaScript. Pass a function to the interval timer rather than a string of executable code.
Test the behaviour
Check that the clock updates after the page loads, that the date rolls over correctly, and that its label states the time zone honestly. Keep it readable without animation and do not make a visitor depend on a decorative clock to understand essential information.
Related guides
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function updateClock (){
var currentTime = new Date ( );
var currentHours = currentTime.getHours ( );
var currentMinutes = currentTime.getMinutes ( );
var currentSeconds = currentTime.getSeconds ( ); // Pad the minutes and seconds with leading zeros, if required
currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;
// Choose either "AM" or "PM" as appropriate
//var timeOfDay = ( currentHours < 12 ) ? "AM" : "PM";
// Convert the hours component to 12-hour format if needed
currentHours = ( currentHours > 12 ) ? currentHours - 12 : currentHours;
// Convert an hours component of "0" to "12"
currentHours = ( currentHours == 0 ) ? 12 : currentHours;
// Compose the string for display
var currentTimeString = "PARIS, " + currentHours + ":" + currentMinutes + " ";
$("#clock").html(currentTimeString);
}
$(document).ready(function(){
setInterval('updateClock()', 1000);
});
</script>
<div id="clock"></div>
0 Comments