Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 7 of 7
  1. #1
    New to the CF scene
    Join Date
    May 2012
    Posts
    5
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Looped Weekly Javascript countdown (auto-reset)

    Hello.

    I open a new forum thread as adviced by jmrker.

    Old forum thread related to this topic:
    http://www.codingforums.com/showthre...8#post12243889




    Here is my code, based on the latest Philip M's work :
    Code:
    <html>
    <head>
    
    <script type = "text/javascript">
    
    var cday;
    var timeInSecs;
    var ticker;
    
    function getSeconds() {
    var now = new Date();
    var nowtime= now.getTime();  // time now in milliseconds
    var countdowntime = new Date(now.getFullYear(),now.getMonth(),now.getDate(),20,0,0); //  16 hrs = 4 pm
    // countdowntime - change time hh,mm,ss to whatever time required, e.g. 7,50,0 (0750)
    
    var dy = 5 ; // Friday (day 5) - change for other days 0-6
    var atime = countdowntime.getTime();
    var diff = parseInt((atime - nowtime)/1000);  // positive if date is in future
    if (diff >0) {
    cday = dy - now.getDay();      
    }
    else {
    cday =  dy - now.getDay() -1;
    }
    if (cday < 0) { cday += 7; }   // aleady passed countdown time, so go for next week
    if (diff <= 0) { diff += (86400 * 7) }
    startTimer (diff);
    }
    
    function startTimer(secs) {
    timeInSecs = parseInt(secs);
    ticker = setInterval("tick()",1000); 
    tick(); // to start counter display right away
    }
    
    function tick() {
    var secs = timeInSecs;
    if (secs>0)   { 
    timeInSecs--; 
    } 
    else { 
    clearInterval(ticker); // stop counting at zero
    getSeconds();  // and start all over again! 
     }
    
    var days = Math.floor(secs/86400);
    secs %= 86400;
    var hours= Math.floor(secs/3600);
    secs %= 3600;
    var mins = Math.floor(secs/60);
    secs %= 60;
    var result = days +':';
    result += ((hours < 10 ) ? "0":"" ) + hours + ":" + ( (mins < 10) ? "0" : "" ) + mins
    + ":" + ( (secs < 10) ? "0":"" ) + secs + "";
    document.getElementById("countdown").innerHTML =  result;
    }
    </script>
    </head>
    
    
    
    
    	
    	<body onload = "getSeconds()" style="background-color: #ffffff;">
    	
    	
    	
    		<br><br>	
    		
    		<div id="CountDownLogo" style="background-color: #ffffff; width:300px; height: 180px; background-image:url(ScreenShot002.png) ">
    			<span id="title" style="font-family: arial; font-size: 20; font-weight: bold; color: #ffffff; position: relative; top:27px; left:60px; z-index:1;">Weekend Cup 2012</span>
    			<br><br>
    			<span id="countdown" style="font-family: arial; font-size: 25; font-weight: bold; color: #3b3b3b; position: relative; top:34px; left:127px; z-index:1;"> </span>			
    			<br><br>
    		
    		</div>		
    		
    		
    		
    	</body>
    	
    	
    	
    	
    	
    </html>
    My event takes place at 8pm on fridays.
    To see if this script works in all conditions, I change my system date and time (to see if the script displays the good remaining duration).

    TESTS:
    Friday
    - So I set my system date on friday but at different times. When I do that, everything seems to work fine.
    - If I chose an earlier time (11am for example), it's fine too.
    - If I chose 7:59:45 pm (and wait a few seconds) I can see the countdown resetting and displaying 6 days 23 hours 59 min 59 sec. So it's fine too.

    Saturday
    - But if I chose saturday 00:00:01 am it doesn't work. It displays 0:19:59:59 (as if the event occured the same day, saturday).
    - And if I chose saturday 7:59:45 pm, the counter resets and displays 6 days 23 hours 59 min 59 sec.. Which is also wrong because it would mean that the even occurs on saturdays 8pm.

    Sunday
    - Same for sunday (the same errors like saturdays)


    Btw, could it be possible to display on the HTML page, all variable values ?
    This could help me understand how the script is done. (I am a poor coder).

    Thank you very much.

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,200
    Thanks
    75
    Thanked 4,342 Times in 4,308 Posts
    Here's my way of doing it. It includes a <form> where you can put in any date and time and see what the answer is.
    Code:
    <!DOCTYPE html>
    <html>
    <head>
    <script type="text/javascript">
    var EVENTDAY = 5; // friday
    var EVENTHOUR = 20;
    
    function getRemaining( now )
    {
        if ( now == null ) now = new Date();
    
        var dow = now.getDay();
        // the "hour" for now must include fractional parts of the hour, so...
        var hour = now.getHours() + now.getMinutes()/60 + now.getSeconds()/3600;
    
        // how many days from current day until event day?
        var offset = EVENTDAY - dow;
    
        // if event day is past *OR* if today is the event day but the event time is past...
        if ( offset < 0 || ( offset == 0 && EVENTHOUR < hour ) )
        {
            // we are past the event time in current week, so 
            // target EVENTDAY is next week:
            offset += 7; 
        }
    
        // so this date (day of the month) is the next occurrence of the event:
        var eventDate = now.getDate() + offset; 
    
        // and so then next occurrence of the event is at this time:
        var eventTime = new Date( now.getFullYear(), now.getMonth(), eventDate, 
                                  EVENTHOUR, 0, 0 ); 
    
        // this is how many milliseconds from now to the next event occurrence
        var millis = eventTime.getTime() - now.getTime();
    
        // convert milliseconds to days/hours/minutes/seconds:
        var seconds = Math.round( millis / 1000 );
        var minutes = Math.floor( seconds / 60 );
        seconds %= 60;
        var hours = Math.floor( minutes / 60);
        minutes %= 60;
        var days = Math.floor( hours / 24 );
        hours %= 24;
        if ( seconds < 10 ) seconds = "0" + seconds;
        if ( minutes < 10 ) minutes = "0" + minutes;
        if ( hours < 10 ) hours = "0" + hours;
      
        // and return that formatted pretty:
        return days + " days, " + hours + ":" + minutes + ":" + seconds;
    }
    
    function tick()
    {
        // this is the automatic once a second display:
        document.getElementById("countdown").innerHTML = getRemaining();
    }
    setInterval( tick, 1000 ); // specifies once a second
    
    // here is a demo that allows you to test the function 
    // by specifying a date and time in the <form> below
    function demo( form )
    {
        var t = form.theDate.value.split("/");
        var mn = Number(t[0]);
        var dy = Number(t[1]);
        var yr = Number(t[2]);
        var t = form.theTime.value.split(":");
        var hr = Number(t[0]);
        var mi = Number(t[1]);
        var sc = Number(t[2]);
        // so this is the test date/time that you specified:
        var test = new Date( yr, mn-1, dy, hr, mi, sc );
    
        // and here we call the master function and put its answer in the <form>:
        form.remaining.value = getRemaining( test );
    }
    </script>
    <body>
    Time remaining until Friday at 8 PM: <span id="countdown"></span>
    <hr>
    <form>
    Test the function:<br/>
    Enter date as mm/dd/yyyy <input name="theDate" /><br/>
    Enter time as hh:mm:ss <input name="theTime" /><br/>
    <input type="button" value="Test" onclick="demo(this.form);"/>
    <br/>
    From that date/time to Friday 8PM: <input name="remaining" readonly/>
    </form>
    </body>
    </html>
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #3
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,200
    Thanks
    75
    Thanked 4,342 Times in 4,308 Posts
    To show any of the intermediate values on the page, just add a <span> with an id, like this:
    Code:
    Calculated next event time: <span id="showEventTime"></span>
    And then add a line in the JS code something like this:
    Code:
        ...
        // and so then next occurrence of the event is at this time:
        var eventTime = new Date( now.getFullYear(), now.getMonth(), eventDate, 
                                  EVENTHOUR, 0, 0 ); 
    
        document.getElementById("showEventTime").innerHTML = eventTime.toString();
    
        // this is how many milliseconds from now to the next event occurrence
        var millis = eventTime.getTime() - now.getTime();
        ...
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    xanax (05-08-2012)

  • #4
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,919
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    For the record, here is jmrker's script corrected:-

    Code:
    <html>
    <head>
    
    <script type = "text/javascript">
    // From: http://www.codingforums.com/showthread.php?t=187335  jmrker corrected by Philip M 
    
    var cday;
    var timeInSecs;
    var ticker;
    
    function getSeconds() {
    var now = new Date();
    var dy = 5 ; // Friday (day 5) - change for other days 0-6  as required
    var countdowntime = new Date(now.getFullYear(),now.getMonth(),now.getDate(),16,0,0); //  16 hrs = 4 pm
    // countdowntime - change time hh,mm,ss to whatever time required, e.g. 7,50,0 (0750)
    
    var nowtime= now.getTime();  // time now in milliseconds
    var atime = countdowntime.getTime();  // countdown time in milliseconds
    var diff = parseInt((atime - nowtime)/1000);  // positive if countdowntime is in future
    if (diff > 0) { cday = dy - now.getDay() }    
    else { cday =  dy - now.getDay() -1 }  //  already passed countdown time
    if (cday < 0) { cday += 7; }   // aleady passed countdown time, so go for next week
    if (diff <= 0) { diff += (86400 * 7) }  // move on one week
    startTimer (diff);
    }
    
    function startTimer(secs) {
    timeInSecs = parseInt(secs);
    ticker = setInterval("tick()",1000); 
    tick(); // to start counter display right away
    }
    
    function tick() {
    var secs = timeInSecs;
    if (secs>0)   { 
    timeInSecs--; 
    } 
    else { 
    clearInterval(ticker); // stop counting at zero
    getSeconds();  // and start all over again! 
     }
    
    var days = Math.floor(secs/86400);  // redundant
    secs %= 86400;
    var hours= Math.floor(secs/3600);
    secs %= 3600;
    var mins = Math.floor(secs/60);
    secs %= 60;
    var result = "Time remaining " + cday +' day(s) ';
    result += ((hours < 10 ) ? "0" : "" ) + hours + " hours " + ( (mins < 10) ? "0" : "" ) + mins
                    + " minutes " + ( (secs < 10) ? "0" : "" ) + secs + " seconds";
    document.getElementById("countdown").innerHTML =  result;
    }
    </script>
    </head>
    
    <body onload = "getSeconds()">
    <span id="countdown" style="font-size: 20; font-weight:bold;" > </span>
    </body>
    </html>

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #5
    New to the CF scene
    Join Date
    May 2012
    Posts
    5
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Thank you all for your help.

    Both scripts work except that Philip M's code needs a page refresh if I change the system date/time and not Old Pedant's. But I agree, it doesn't matter at all. Thank you !
    Also, a special thank you fot Old Pedant's comments in his code. Now, it's useful for me to understand your logic.

    Now that I have a countdown as a "text" (digits in fact), how hard would it be to mix this script with another one that would show different images in the background, according to the remaining time?

    I meant something like the Ubuntu Countdown logos :
    http://martincesare.com.ar/ubuntu-10...er-javascript/
    http://www.martincesare.com.ar/wp-co...s/countdown.js

    These "animated" logos are based on different images (one per day left).

    Here is a mockup image of what I plan to add to my website :


    Hehe, I would like the cigar to get shorter each day.
    I guess 7 images could be enough (one per day) or 14, twice a day.

  • #6
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,919
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    Very easy. Simply add to the end of the script the two lines in blue:-

    document.getElementById("countdown").innerHTML = result;
    var img = ["Zero.jpg","One.jpg", "Two.jpg","Three.jpg", "Four.jpg","Five.jpg","Six.jpg"];
    document.getElementById("myimage").src = img[cday];

    }

    and in the <body>

    <img id = "myimage">

    Obviously the 7 images which correspond to the days remaining 0-6 can be assigned whatever names you wish.

    You could easily extend this to 14 images by taking hours into account, and if hours >= 12 then add 7 to the index.

    Code:
    var x = cday;  // days remaining 0-6 
    if (hours >=12) {x += 7}  // to make 7-13 when hours >= 12
    document.getElementById("myimage").src = img[x];
    There is no need to change your system date and time if you want to test the script. Just change the values in the script to (say) 2 minutes from now.
    Last edited by Philip M; 05-05-2012 at 04:58 PM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • Users who have thanked Philip M for this post:

    xanax (05-08-2012)

  • #7
    New to the CF scene
    Join Date
    May 2012
    Posts
    5
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Sorry to bother you guys, but what if I would like the same script but for events that occur every 2 months and 15 days ?


  •  

    Posting Permissions

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