www.webdeveloper.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 19

Thread: Adjusting my clock script

  1. #1
    Join Date
    Jul 2014
    Posts
    16

    Adjusting my clock script

    Hi everyone,

    I had to build a clock that appears in the browser status bar. The task required me to have a button on the page that when clicked would switch the time from 12-hour format to 24-hour format. For example: 8:24am turns to 08:24 after one click and back to 8:24am after a second click.

    I have the code working to show the time in 12-hour format accurately in the status bar, but I can't figure out how to create a button to switch between 12-hour and 24-hour format if anyone could lend a suggestion.

    Here's my code (I have a button there but nothing attached of course):

    Thanks everyone

    Code:
    <html>
    <head>
    <title>Clock</title>
    <script Language="JavaScript">
    var timerID = null;
    var timerRunning = false;
    
    function stopclock (){
    if(timerRunning)
    clearTimeout(timerID);
    timerRunning = false;
    }
    
    function showtime () {
    var now = new Date();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var seconds = now.getSeconds()
    var timeValue = "" + ((hours >12) ? hours -12 :hours)
    timeValue += ((minutes < 10) ? ":0" : ":") + minutes
    timeValue += (hours >= 12) ? " P.M." : " A.M."
    window.status = timeValue;
    timerID = setTimeout("showtime()",1000);
    timerRunning = true;
    }
    
    function startclock () {
    stopclock();
    showtime();
    }
    
    </script>
    </head>
    <body>
    <BODY onLoad="startclock()">
    <input type="button" name="switch" value="Adjust Time">
    </body>
    <form name="clock" onSubmit="0">
    </html>

  2. #2
    Join Date
    Nov 2010
    Posts
    1,090
    you are doing yourself a great disservice by copying (ancient) code from the web without understanding it, and an even greater one by getting people on forums to do your assignments for you. How will you ever learn?

    Basically:
    - set a flag for if you want 24 or 12 hour display
    - find the part in your code that converts 24 hour to 12 hour
    - only get that code to run if your flag is set to 12 hour
    - make the button fire a function that switches the flag and re-displays the time

    on a side note, window.statusbar is (afaik) only supported by opera. Personally, I would go for document.title

  3. #3
    Join Date
    Jul 2014
    Posts
    16
    Quote Originally Posted by xelawho View Post
    you are doing yourself a great disservice by copying (ancient) code from the web without understanding it, and an even greater one by getting people on forums to do your assignments for you. How will you ever learn?

    Basically:
    - set a flag for if you want 24 or 12 hour display
    - find the part in your code that converts 24 hour to 12 hour
    - only get that code to run if your flag is set to 12 hour
    - make the button fire a function that switches the flag and re-displays the time

    on a side note, window.statusbar is (afaik) only supported by opera. Personally, I would go for document.title
    It was the only working example I could find to play around with unfortunately that I could break apart. But judging by some of your reply, I'm guessing this isn't a good example to use to understanding things?

    As far as the converting between 12 and 24 hour code, would I want to basically insert some conditional logic to say "if we are in 24 hr mode, format the string this way, else format the string this way" and store that in a global variable that the button toggles?

  4. #4
    Join Date
    Nov 2010
    Posts
    1,090
    Quote Originally Posted by Minnesota31 View Post
    It was the only working example I could find to play around with unfortunately that I could break apart. But judging by some of your reply, I'm guessing this isn't a good example to use to understanding things?
    it's an OK example. What marks it as ancient are things like <script Language="JavaScript">, the javascript in the head and the superweird "BODY onLoad"

    Quote Originally Posted by Minnesota31 View Post
    As far as the converting between 12 and 24 hour code, would I want to basically insert some conditional logic to say "if we are in 24 hr mode, format the string this way, else format the string this way" and store that in a global variable that the button toggles?
    you could do that. I don't know why you would need to make it a global variable - just get your button to call the startclock function again. Your showtime function is already doing all the work you need it to.

  5. #5
    Join Date
    Jun 2004
    Location
    Portsmouth UK
    Posts
    2,689
    Code:
    <html>
    <head>
    <title>Clock</title>
    <script type="text/javascript">
    
    function showtime(m) {
     clearTimeout(showtime.to);
     if (m){
      var now=new Date(),hours = now.getHours(),minutes = now.getMinutes(),seconds= now.getSeconds(),hours=hours >12&&m=='12'?hours -12 :hours
      var timeValue = (hours<10?'0':'' )+hours;
      timeValue += ((minutes < 10) ? ":0" : ":") + minutes
      timeValue += m=='12'? (hours >= 12) ? " P.M." : " A.M.":'';
      window.status = timeValue;
      showtime.to = setTimeout(function(){ showtime(m); },1000);
     }
    }
    
    </script>
    </head>
    <body onload="showtime('12');">
    <input type="button" name="switch" value="Adjust Time 24" onclick="showtime('24');">
    <input type="button" name="switch" value="Adjust Time 12" onclick="showtime('12');">
    
    </body>
    </html>
    Vic

    God loves you and will never love you less.

    http://www.vicsjavascripts.org/Home.htm
    If my post has been useful please donate to http://www.operationsmile.org.uk/

  6. #6
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,414
    Or this method should do the trick...
    HTML Code:
    <html>
    <head>
    <title>Clock</title>
    <script type="text/javascript">
    
    timer = {
    	format:false,
    	update:function(){
    		var theDate = new Date().toUTCString();
    		timer.theTime = theDate.slice(17,25);
    		// if we are a 12 hour format, we need to run this set of elements
    		if(timer.format){
    			var tmp = timer.theTime.split(":"); 
    			var ord = (tmp[0]-0)>12 ? "PM" : "AM"; // create an ordinal value
    			tmp[0] = tmp[0]>12 ? (tmp[0]-12) : tmp[0];
    			timer.theTime = tmp.join(":")+" " +ord; // add the ordinal
    		}
    		timer.to.innerHTML = timer.theTime;
    	
    	},
    	toggle:function(){
    		// toggle the time format
    		this.format = !this.format;
    	},
    	init:function(){
    		if( timer.to=document.getElementById("to") ){
    			clearTimeout(timer.auto);
    			timer.auto = setInterval(timer.update,999); // 0 to 999 = 1000ms
    			
     		}
    	},
    	auto:setInterval('timer.init()',1000)
    }
    </script>
    </head>
    <body>
    <input type="button" name="switch" value="Toggle Format" onclick="timer.toggle();">
    <div id="to"></div>
    </body>
    </html>
    *untested in hours less than 12*
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

  7. #7
    This might be a silly question -- but what browsers even HAVE status bars anymore, much less let you change what's in them from .js?

    Just saying...

    Figured I'd throw my hat into the ring on this one -- just so you can see even more different ways of doing it. It's actually better to learn as many different approaches as you can, then select the one that's best for you.

    For me, I don't like putting things in the markup that only work when scripting is enabled -- confuses users when they see controls that don't work; for all the scripttard claims of how "everyone has javascript" -- many users don't trust it, intentionally block it, or just plain get pissed off by it. The several million people who install the 'noscript' extension for FF for example -- or "real" Opera users with the built-in per-site script blocking/enabling.

    Which is why I'd start out with a pretty much empty HTML document with a warning behind a NOSCRIPT before even THINKING about scripting functionality. I'd also have the script in an external file so I don't have the headaches of seeing HTML and JS at the same time... or if I want to see them at the same time I can edit them in separate windows side-by-side! (which is WAY easier than the constant scrolling up and down garbage). Since in production code scripting usually has no blasted business in the HTML in the first place -- you might as well start at the finish line; it's just easier that way. Though I know most people for some weird reason don't seem to see it that way...

    Since most modern browsers don't even show a status bar, much less let you change it's value, I'd probably change window.document.title instead. Save the existing title, and on update append the time to it. Also cute since it will show as the text on the tab.

    Let's see... Yeah, here we go:

    http://www.cutcodedown.com/for_other...ock/clock.html

    As with all my examples the directory:

    http://www.cutcodedown.com/for_others/Minnesota31/clock

    is unlocked for easy access to the gooey bits and pieces. The Script itself:

    http://www.cutcodedown.com/for_other...clock/clock.js

    Not too complex... but let's give you a general overview of what it's doing:

    function make -- I added this so it's easier to generate the controls from the DOM, and since we make them ourselves it's easier to attach the onclick handlers and plug them into the parent as needed.

    function padZero -- simple routine to make sure numbers are leading padded with zeros to however many places you need.

    var textReplace -- is actually a function. We 'could' just use .textContent if we didn't care about legacy browsers (basically IE)... but detecting if textContent exists and then making this a function of the appropriate version results in a routine that's a hair faster when we're calling it than it would be if we ran that if statement inside the function every time.

    function makeControl -- since the two controls share so much in common, and you might want other controls similar in nature, make a function to generate them that plugs in all the 'common' bits to 'make'.

    function showTime -- pretty much what you had. I have the boolean variable "timer12" to say if it's 12 hour format, if false it's 24 hour. Again since nothing I use will even show 'status' anymore, I went with the TITLE instead.

    var originalTitle -- saved so we can prepend it to the time.

    var timer12 -- the bool to determine the time format.

    var timerId -- the interval handler. I use setInterval instead of setTimeout so we don't have to waste time doing that inside showTime.

    var controls -- just a container DIV for our control anchors. I'm using anchors since this is NOT a form; no matter how many scripttards do so, it is NOT correct to be using form elements for non-form actions. Anchor is much closer in terms of a generic interface element.

    var swap1224 -- the anchor for changing the time format. We use makeControl to create it with the starting title, and attach our handler function. Said function simply does a textReplace on itself, swapping timer's value inside the same inline-evaluation used to determine if we should be showing "24" or "12". We then call showTime to immediately update the displayed time instead of waiting for the setInterval.

    var updateStopStart -- the anchor for stopping and starting the counter updates. I like to set to an explicit "false" as not all browsers null a timer handler when you clear it -- if we start the timer it helps to immediately show it, since even that second delay can make users think it's busted. Finally it too does a text-replace based on the timer state so as to show the correct text inside the control.

    Finally, I call showTime to immediately show the time, instead of waiting that full second.

    ... and it's all wrapped in a nice neat anonymous function so nothing it does will risk namespace collisions should you use this code alongside other scripts. I also pass 'document' to it as 'd' so we can save a few bytes on typing 'document' all the blasted time. (A trick I picked up from Google's codebase)

    Hope this helps.
    Last edited by deathshadow; 07-31-2014 at 03:26 AM.

  8. #8
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,414
    Waiting a full second? You don't have to wait a full second, you only need alter the set timer value to 1 ms if you want to, not that its practical to do that because you need to factor in that some web pages take several seconds to load fully and its also important to note that JavaScript is not instantly executed just because its in an anonymous function either.
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

  9. #9
    Quote Originally Posted by \\.\ View Post
    Waiting a full second? You don't have to wait a full second, you only need alter the set timer value to 1 ms if you want to, not that its practical to do that because you need to factor in that some web pages take several seconds to load fully and its also important to note that JavaScript is not instantly executed just because its in an anonymous function either.
    If that's in reference to my code, you completely misunderstand it. It uses SETINTERVAL, it would be asenine to run an interval flat out on something that only needs second precision. Simply calling showtime manually prevents that delay when using intervals. If it were using timeouts, THEN what you are saying might make sense... though it really doesn't.

    You do know the difference between an interval and a timeout, right? Apparently not...

    ... and again, you put scripting before </body> it will run before CSS is applied in everything but gecko based browsers, where it still has an 80% chance of doing so if the script is playing with the DOM. It also typically tends to load the page WAY faster unless you're doing stupid crap like having code that waits for onload when it doesn't need to.

  10. #10
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,414
    Quote Originally Posted by deathshadow View Post
    If that's in reference to my code, you completely misunderstand it. It uses SETINTERVAL, it would be asenine to run an interval flat out on something that only needs second precision. Simply calling showtime manually prevents that delay when using intervals. If it were using timeouts, THEN what you are saying might make sense... though it really doesn't.

    You do know the difference between an interval and a timeout, right? Apparently not...

    ... and again, you put scripting before </body> it will run before CSS is applied in everything but gecko based browsers, where it still has an 80% chance of doing so if the script is playing with the DOM. It also typically tends to load the page WAY faster unless you're doing stupid crap like having code that waits for onload when it doesn't need to.
    I personally don't use onload unless I am demonstrating it and it is sometimes a good idea to wait for an onload event trigger where a set of functions that needs the full DOM to have loaded first to be ready and waiting. My personal preference is to call for an element and if not available, redial... in the example I gave, I would normally include a checking counter to see iff the object has reached a point where it obviously is not available, eg, like after 20 seconds, then that particular function then gets killed off.

    I certainly do know the difference between an interval and a timeout and in reference to "your code", yes I do understand it but I don't understand why you need bloatware included.

    You do know what KISS is? and I am not referring to that rock band from the 70's.

    To help you understand my reply, it was to your comment about waiting a second which I can only assume was in reference to the code example I displayed, this being a simple clock that allows toggle between 12 and 24 hour, the simplicity of it comes from slicing out the time and not using .getHours() at al to be manipulated, you save the need to pad anything because it already comes with leading zeros which can be discarded if not needed.

    The initial pause may be a full second, it doesn't have to be, it can be 1ms, 10ms or 100ms (or in otherwords 'as needed') which runs until the display object is hooked where the timer is then cleared and another timer takes its place using the same variable, reuse is much tidier and speedier than having to make yet another variable which eats memory and time.

    Again you are banging on about this reference to putting scripts before the <body> which I have to point out to you is where a JavaScript is meant to live, in the <head> of the document, who cares about CSS formatting a page and then having javascript access elements, it really makes little difference in terms of looks because it doesn't matter what browser you use, the box method looks awful until CSS has got its act together, something that you will see on a slow internet connection (yes 56k still exists in some parts of the world even now) and document loading is a matter of how the internet delivers the various packets, so no matter how well you make your anonymous scripts, the law of the internet transport control protocol rules (some people like to call it Transmission Control Protocol).

    Its been a number of years since I have used my network administration training, the underlying principles of how the internet works remains the same, in many cases internet connections have sped up but the protocols in play have not changed much in how they operate.

    So with the best coding a web page has, tcp can cause the page packets to arrive in any order, some data may need to be re-transmitted again because it never arrives or was found corrupt and wasn't recoverable. TCP transfer is designed with sequential transport in mind however it may not arrive in the order it was sent due to the nature of routing of packets. You might want to consider this fact the next time you start banging on about where I and the larger portion of web programmers shove our code.
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

  11. #11
    Quote Originally Posted by \\.\ View Post
    To help you understand my reply, it was to your comment about waiting a second which I can only assume was in reference to the code example I displayed
    Why can you 'only assume that' -- the comment had to do with setInterval 1000 taking a second, so rather than wait show it now. It had NOTHING to do with your code, it had to do with MY using setInterval instead of setTimeout.

    Quote Originally Posted by \\.\ View Post
    this being a simple clock that allows toggle between 12 and 24 hour, the simplicity of it comes from slicing out the time and not using .getHours() at al to be manipulated, you save the need to pad anything because it already comes with leading zeros which can be discarded if not needed.
    Which is a slick way of doing it actually... I hadn't really noticed you did that, and that IS a superior way of handling it. We could probably even improve that further by not using SPLIT, since JS arrays are the most painfully slow thing in the entire language.

    BUT, you want to talk yours -- You have several bugs. Hours > 12 that resolve to 0..9 lose their leading 0, as you're testing > 12 and not > 11 you'll have TWO 12AM's, and I'm not sure how useful GMT is going to be to people not in the UK -- you probably should have used toString instead of toUTCString -- well, unless you really want GMT shown everywhere.

    Still, I do like processing the string, I'd just use toString instead of toUTCString since rarely do you want GMT over localtime. I probably also wouldn't attach values to the parent method, sadly the creation of a local var is usually faster than the dual lookup of an object method, since locals are parsed first.

    So something like...

    Code:
    	update:function(){
    		var time = new Date().toString().substr(16,8);
    		// if we are a 12 hour format, we need to run this set of elements
    		if (timer.format) {
    			time = time.split(':'),
    			var
    				hours = Number(time[0]),
    				AMPM = hours > 11 ? ' PM' : ' AM';
    			if (hours > 11) hours -= 12;
    			if (hours == 0) hours = 12;
    			time[0] = (hours < 10 ? '0' : '') + hours;
    			time = time.join(':') + AMPM;
    		}
    		textReplace(timer.to, time);
    	},
    Quote Originally Posted by \\.\ View Post
    reuse is much tidier and speedier than having to make yet another variable which eats memory and time.
    Not even having to play with setTimeout during the timer handler would use even less.

    Quote Originally Posted by \\.\ View Post
    Again you are banging on about this reference to putting scripts before the <body>
    </body> you mean.

    Quote Originally Posted by \\.\ View Post
    which I have to point out to you is where a JavaScript is meant to live, in the <head> of the document
    ... and where in any specification does it say that? The specification most certainly says it for the STYLE tag, but the SCRIPT tag? Not so much. Scripting can go anywhere, for good reason.

    You want to play with DOM elements, you put it in HEAD you have to at least wait for DOMContentLoaded, or as most people do ONLOAD. You do it right before </body>, the DOM is built and you can just start doing it. It's simpler AND faster, and loads smoother. What your problem is with that is beyond me.

    Quote Originally Posted by \\.\ View Post
    something that you will see on a slow internet connection (yes 56k still exists in some parts of the world even now)
    That part is good for a laugh - it's one of the arguments I use in favor of my approach, since again it loads faster and smoother and usually uses less code if you're playing with the DOM or plugging in values.

    Quote Originally Posted by \\.\ View Post
    and document loading is a matter of how the internet delivers the various packets, so no matter how well you make your anonymous scripts, the law of the internet transport control protocol rules (some people like to call it Transmission Control Protocol).
    which has jack **** to do with the topic since TCP dicates just how the files are passed, NOT the order in which they are loaded by the document, or how the browser renders them. That's a straw man argument at best.

    I don't know where you got this idea that scripts "go in the head only" or that doing so is going to be any better. It's pretty much standard practice now to put them in BODY right before you close it, so they load faster and render smoother -- that you seem to be railing against this practice for no fathomable reason is just... wow man... wow.

    ... and a quick google of it shows all the arguments against putting it in body are a decade old, refer to the outdated practice of document.write, or are more FUD than fact.

    You want to manipulate the DOM without resorting to onload, where else are you going to put it? Have fun with document.getElementById running the chance of bombing because you ran it too soon. (which I've seen people do!)

    Much like the arguments against using anonymous functions, it's a bunch of nonsensical bull that isn't even based in reality.

    That said, I'm gonna rewrite my script to use that string method on Date -- 'cause that is slick; be slicker once the logic bugs are squashed.
    Last edited by deathshadow; 08-01-2014 at 09:43 PM.

  12. #12
    ... and here we are adjusted to use //./'s cool string technique, with some changes so it gets all the little details correct.

    Code:
    	function showTime() {
    		var time = new Date().toString().substr(16,8);
    		if (timer12) {
    			time = time.split(':');
    			var
    				hour = Number(time[0]),
    				AMPM = (hour > 11) ? ' PM' : ' AM';
    			if (hour > 11) hour -= 12;
    			if (hour == 0) hour = 12;
    			time[0] = (hour < 10 ? '0' : '') + hour;
    			time = time.join(':') + AMPM;
    		}
    		window.document.title = originalTitle + ' - ' + time;
    	}
    Which I uploaded to the live copy:
    http://www.cutcodedown.com/for_other...esota31/clock/

    Side note, anyone else ever think it was odd that midnight is 12 AM, followed by 1AM, while 11AM is followed by 12PM followed by 1PM? Just exactly who thought that was a good idea?

    http://www.englisch-hilfen.de/en/words/uhr.htm -- site that explains it... 12:59 PM is followed by 1:00 PM. Confusing as hell.

    Guess there's a reason I use 24 hour/military time.
    Last edited by deathshadow; 08-01-2014 at 09:54 PM.

  13. #13
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,414
    Javascript has always lived in the head of a web document, if you have been coding long enough you will see that this is how coding is done.

    I really don't know what your problem is and any ideas I propose are just ideas unless I state categorically that it has been fully tested, it is up to the person requesting help to test and return any operational problems.

    I have more important things to be getting on with rather than dealing with your bickering and whining, if you can be bothered to change your attitude towards the people asking for help rather than pulling them up for really minor issues that are perfectly acceptable, you might just make the man of the year awards.
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

  14. #14
    Quote Originally Posted by \\.\ View Post
    Javascript has always lived in the head of a web document, if you have been coding long enough you will see that this is how coding is done.
    Since WHEN. WHERE DID YOU GET THIS NONSENSE FROM?!? If it only 'lives in the head' why does document.write even EXIST? Why does the specification for the tag itself read:

    http://www.w3.org/TR/html4/interact/...ml#edef-SCRIPT
    The SCRIPT element places a script within a document. This element may appear any number of times in the HEAD or BODY of an HTML document.
    hence why a good reference like this one for the folks who can't grasp the spec:
    http://htmlhelp.com/reference/html40...al/script.html

    Says:
    Contents An embedded script
    Contained in HEAD, block-level elements, inline elements except SELECT and SCRIPT
    Quote Originally Posted by \\.\ View Post
    I really don't know what your problem is
    You keep saying things that have nothing to do with reality, the specifications, or even really helps anyone. You seem to keep saying completely unrelated bull and outright lies not supported by any facts. That's my problem.

    Script can go anywhere, loading it before </body> means less scripting needed as you don't have to wait for onload to play with elements on the DOM or add to the markup/DOM, and typically loads the page faster and makes that load render smoother. Anyone telling you otherwise is packing you so full of sand you could change your name to Sahara.

    Deal with it!

  15. #15
    Join Date
    Nov 2010
    Posts
    1,090
    http://htmlhelp.com/reference/html40...al/script.html
    Typically the SCRIPT element is used in the HEAD unless it generates BODY content.
    Probably not the best source to be quoting from, but to be fair it does look like it was written in 2006.

    That said, I agree - there are a few specialised cases where the script should go in the HEAD, but for everyday use, just before the end BODY tag is almost always the best place for it to be.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles