Jump to content

I have a javascript countdown timer but would like to know how to add a cookie to it


Go to solution Solved by imgrooot,

Recommended Posts

Simply put, I would like the countdown timer to NOT reset if the page is refreshed.  From what I know, I have to use cookies for that. Can you tell me how I can incorporate a cookie in the following code?

 

I am using this example. http://www.onextrapixel.com/2011/12/01/creating-a-groupon-like-count-down-timer/

 

The setup is like this. 

<html>
<head>
<!-- 1 -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="timer.js"></script>

<!-- 3 -->
<script>
	$(document).ready(function(){		
		var timeLeft = 12796000; // this is in milliseconds.	
		var timer =  new Timer($('#counter'), timeLeft);		
	});
</script>

<!-- 4 -->
<style>
div#counter{
	margin: 100px auto;	
	width: 305px;	
	padding:20px;
	border:1px solid #000000;
}
div#counter span{
	background-color: #00CAF6;
	padding:5px;
	margin:1px;
	font-size:30px;
}
</style>

</head>
<body>

<!-- 2 -->
<div id="counter">	
	<span class="hour">00</span>
	<span class="min">00</span>
	<span class="sec">00</span>
</div>

</body>
</html>

timer.js

function Timer(container, timeLeft) {
  // get hour, minute and second element using jQuery selector
  var hoursContainer = $(container).find('.hour');
  var minsContainer  = $(container).find('.min');
  var secsContainer  = $(container).find('.sec');
   
  // hold time left
  var currentTimeLeft = timeLeft;
  // 1 second = 1000 ms
  var secondsForTimer = 1000;  
  // hold ID value return by setInterval()
  var timerInterval;
  
  // call setInteval() only when timeLeft is greater than 0
  if (currentTimeLeft == 0) {
	  return;
  } else {
	  //Call setInterval()function and store ID value to timerInterval. 
	  timerInterval = setInterval(countdown, secondsForTimer);
  }
  
  //function being passed to setInterval()
  function countdown() {
    currentTimeLeft = parseInt(currentTimeLeft - secondsForTimer);    
    if (currentTimeLeft == 0) {
       //stop calling countdown function by calling clearInterval()
       clearInterval(timerInterval);
       return;
    } else {    	
       //calculate hours left
       var wholeSeconds = parseInt(currentTimeLeft / 1000,10);
       var wholeMinutes = parseInt(currentTimeLeft / 60000,10);
       var wholeHours   = parseInt(wholeMinutes / 60,10);
       //calculate minutes left
       var minutes = parseInt(wholeMinutes % 60,10);
       //calculate seconds left
       var seconds = parseInt(wholeSeconds % 60,10);
       //prefix 0 to hour, min and second counter
       $(hoursContainer).text((wholeHours < 10 ? "0" : "") + wholeHours + (wholeHours <=0 ? " hr" : " hrs"));
       $(minsContainer).text((minutes < 10 ? "0" : "") + minutes  + (minutes <=0 ? " min" : " mins"));
       $(secsContainer).text((seconds < 10 ? "0" : "") + seconds  + (seconds <=0 ? " sec" : " secs"));
    }
  }
}

You don't need to use cookie at all.

 

All you need to do is to dynamically calculate the  timeLeft  value by subtracting todays date/time from your target date/time.

 

For example if you want your timer to countdown until 8pm today (16th October 2015). Then do

// get todays date
today = new Date();			

// the target date, this will get the date/time for 8PM 16th October 16th 2015
targetDate = new Date(2015, 9, 16, 20);

// subtract the two dates to get the difference in millisecons
var timeLeft = targetDate - today;

 

You don't need to use cookie at all.

 

All you need to do is to dynamically calculate the  timeLeft  value by subtracting todays date/time from your target date/time.

 

For example if you want your timer to countdown until 8pm today (16th October 2015). Then do

// get todays date
today = new Date();			

// the target date, this will get the date/time for 8PM 16th October 16th 2015
targetDate = new Date(2015, 9, 16, 20);

// subtract the two dates to get the difference in millisecons
var timeLeft = targetDate - today;

 

Ahh yes that does work. 

 

Now my question is, since you are using two dates to find the difference in time left, how can I properly add the php date into the javascript "targetDate"? I can't seem to get it to work.

 

Here is the full code.

 // this is the date format when adding to mysql db
$target_date =	date('Y-m-d H:i:s'); 

// this is how the date looks in the html when getting the value from the db
<input type="hidden" class="target-date" value="2015-10-17 00:17:21" />

// this is the variable I am using to get the above input value to the javascript/jquery
var getDate = $(".target-date").val();	


// so all together, this is what the code looks like, with your code included.

<script>
			
	$(document).ready(function(){		
	
		var getDate = $(".target-date").val();	

		// get todays date
		today = new Date();			

		// the target date, this will get the date/time for 8PM 16th October 16th 2015
		targetDate = new Date(2015, 9, 16, 20);

		// subtract the two dates to get the difference in millisecons
		var timeLeft = targetDate - today;
		
		var timer =  new Timer($('#counter'), timeLeft);
		
	});
	
</script>

So the target date is coming from the database. In that case use PHP to calculate the difference between the two dates. Then have PHP set the value for the  timeLeft  javascript variable
 

// subtract the two dates and then multiply by 1000 to get milliseconds
$timeLeft = (strtotime($target_date) - time()) * 1000; 

<script>			
	$(document).ready(function(){
                // echo $timeLeft value to set timeLeft javascript variable
		var timeLeft = <?php echo $timeLeft ; ?>;
		var timer =  new Timer($('#counter'), timeLeft);
	});
	
</script>

 

So the target date is coming from the database. In that case use PHP to calculate the difference between the two dates. Then have PHP set the value for the  timeLeft  javascript variable

 

// subtract the two dates and then multiply by 1000 to get milliseconds
$timeLeft = (strtotime($target_date) - time()) * 1000; 

<script>			
	$(document).ready(function(){
                // echo $timeLeft value to set timeLeft javascript variable
		var timeLeft = <?php echo $timeLeft ; ?>;
		var timer =  new Timer($('#counter'), timeLeft);
	});
	
</script>

 

That does work.

 

One last thing.  I am retrieving multiple records from the db.  Each of the records have their own unique countdown timer.  Right now, it's only showing the countdown timer for the newest record created, while the rest of the records(that are not expired) show 00:00:00.  So I was wondering, what can I do so that the countdown works for all the records?

 

Here is the setup of foreach loop.

foreach($rows as $row) {

	$target_date = $row['target_date'];

	$timeLeft = (strtotime($target_date) - time()) * 1000; 
	
	?>
        <input type="hidden" class="target-date" value="<?php echo $timeLeft; ?>" />
	
	<div id="counter">	
		<span class="hour">00</span>
		<span class="min">00</span>
		<span class="sec">00</span>
	</div>
        <?php
}
Edited by imgrooot

You will have to create a new timers inside the foreach loop. Example

foreach($rows as $k => $row) {

	$target_date = $row['target_date'];

	$timeLeft = (strtotime($target_date) - time()) * 1000; 

        // append the array key to make a unique name for each counter
	$counterName = "counter_$k";
	?>
        <input type="hidden" class="target-date" value="<?php echo $timeLeft; ?>" />

	<div class="counter <?php echo $counterName ?>">	
		<span class="hour">00</span>
		<span class="min">00</span>
		<span class="sec">00</span>
	</div>

        <script>
            // initiate new timer
            new Timer($('.<?php echo $counterName; ?>'), <?php echo $timeLeft; ?>);
        </script>
        <?php
}
  • Solution

 

You will have to create a new timers inside the foreach loop. Example

foreach($rows as $k => $row) {

	$target_date = $row['target_date'];

	$timeLeft = (strtotime($target_date) - time()) * 1000; 

        // append the array key to make a unique name for each counter
	$counterName = "counter_$k";
	?>
        <input type="hidden" class="target-date" value="<?php echo $timeLeft; ?>" />

	<div class="counter <?php echo $counterName ?>">	
		<span class="hour">00</span>
		<span class="min">00</span>
		<span class="sec">00</span>
	</div>

        <script>
            // initiate new timer
            new Timer($('.<?php echo $counterName; ?>'), <?php echo $timeLeft; ?>);
        </script>
        <?php
}

 

 

Can you please double check your above code?  It's giving me an error "ReferenceError: Timer is not defined".

Which is this line.

new Timer($('.<?php echo $counterName; ?>'), <?php echo $timeLeft; ?>);

Make sure you are referencing the timer javascript file (and jquery) before the foreach loop?

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="timer.js"></script>

 

Make sure you are referencing the timer javascript file (and jquery) before the foreach loop?

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="timer.js"></script>

 

 

Ahh yes. I had it in the footer originally.  I didn't think it mattered if I put it in the header or footer, but apparently it does.  It works now.

 

Thank you so much Ch0cu3r.  Your simple steps really made it clear for me to understand. Other wise I would be chasing in circles from all the other tutorials.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.