Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Countdown with PHP

Tags:

javascript

I want to have a countdown associated with a particular button on my PHP page and i am using following code based on javascript But,it resets the target value on page reload,so how to have the same without the target value getting reset.Can i do something with session ??

    <html>
    <body>
<p>Time remaining: <span id="countdownTimer"><span>00:00.<small>00</small></span></p>
<script type="text/javascript">
if (document.getElementById('countdownTimer')) {
    pad = function(n, len) { // leading 0's
        var s = n.toString();
        return (new Array( (len - s.length + 1) ).join('0')) + s;
    };

    function countDown() {
        var now = new Date();
        if ( (now.getDay() >= 0) && (now.getDay() <= 6) ) { // Monday to Friday only
            var target = 23; // 15:00hrs is the cut-off point
            if (now.getHours() < target) { // don't do anything if we're past the cut-off point
                var hrs = (target - 1) - now.getHours();
                if (hrs < 0) hrs = 0;
                var mins = 59 - now.getMinutes();
                if (mins < 0) mins = 0;
                var secs = 59 - now.getSeconds();
                if (secs < 0) secs = 0;
                var str = pad(hrs, 2) + ':' + pad(mins, 2) + '.<small>' + pad(secs, 2) + '</small>';
                document.getElementById('countdownTimer').innerHTML = str;
            }
        }
    }
    var timerRunning = setInterval('countDown()', 1000);
}
</script>
</body>
</html>
like image 673
Ankur Avatar asked Mar 09 '26 12:03

Ankur


1 Answers

Instead of evaluating your variable 'now' as such:

var now = new Date();

Evaluate it like this (assuming our browser supports LocalStorage):

if (!localStorage.myDate)
    localStorage.myDate = (new Date()).toString();
var now = new Date(localStorage.myDate);

This way, we only ever evaluate the current date on first load. After that, we refer to a serialized string version of that date and pass that as an argument when we create our 'now' variable.

If we want to support older browser (cough IE), we can use userData or simply do something very similar with cookies.

like image 83
Graham Robertson Avatar answered Mar 12 '26 01:03

Graham Robertson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!