why is this jQuery not working? - php

I'm having this jQuery script thats adding a timer when someone voted he needs to wait 3 minutes
the script is working till the moment I'm getting the remaining time with php
$(document).ready(function(){
alert("1");
function Timer(dur, par, can, cnt) {
var parent = $(par),
canvas = can ? $(can, parent)[0] : $('.timer', parent)[0],
seconds = cnt ? $(cnt, parent)[0] : $('.counter', parent)[0],
sec = dur,
countdown = sec;
if (!canvas)
canvas = $("<canvas>").addClass('timer')
.attr('width', 100).attr('height', 100).appendTo(parent)[0];
if (!seconds)
seconds = $("<span>").addClass('counter').appendTo(parent)[0];
var ctx = canvas.getContext('2d');
ctx.lineWidth = 8;
ctx.strokeStyle = "#528f20";
var startAngle = 0,
time = 0,
intv = setInterval(function() {
var endAngle = (Math.PI * time * 2 / sec);
ctx.arc(65, 35, 30, startAngle, endAngle, false);
ctx.clearRect(0, 0, 200, 200);
startAngle = endAngle;
ctx.stroke();
countdown--;
if (countdown > 60) {
seconds.innerHTML = Math.floor(countdown / 60);
var ss = countdown % 60;
if (ss < 10)
ss = "0" + ss;
seconds.innerHTML += ":" + ss;
}
else {
seconds.innerHTML = countdown;
}
if (++time > sec, countdown == 0) {
clearInterval(intv);
$(canvas).remove();
$(seconds).remove();
/*$(par).prepend('<img id="theImg" src="http://ivojonkers.com/votify/upvote.png" />');*/
}
}, 1000);}
$(".upvote").click(function(){
alert("2");
var par = $("<div>").addClass("time").appendTo("#timers");
Timer(Math.round(180), par);
});
if (<?php echo $wait; ?> > 0) {
var par = $("<div>").addClass("time").appendTo("#timers");
Timer(Math.round(<?php echo $wait; ?>, par); } });
so in this part I'm getting the time to wait for the next vote with php and this does not seem to work what's going wrong ?
if (<?php echo $wait; ?> > 0) {
var par = $("<div>").addClass("time").appendTo("#timers");
Timer(Math.round(<?php echo $wait; ?>, par); } });

You should just use a setTimeout(function(){},(3 * 60 * 1000)) to block the vote functionality.
//Block the vote here
setTimeout(function(){/*unblock here*/},(3 * 60 * 1000))

Replace this:
Timer(Math.round(<?php echo $wait; ?>, par); } });
With:
Timer(Math.round(<?php echo $wait; ?>, par)); } });
;)

Related

Need help adding "days" to this jquery countdown timer [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I currently have a countdown timer that shows hours, mins, seconds. But now I would like to add "days" to it. Can you please show me how you would do that?
Here's the code. I left out the php db query as it's not important.
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"));
}
}
}
<?php
// db query here to get the expiry time from the database
foreach($results as $k => $row) {
$expiry_date = $row['expiry_date'];
$timeLeft = (strtotime($expiry_date) - time()) * 1000;
$counterName = "counter_$k";
?>
<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
var timer = new Timer($('.<?php echo $counterName; ?>'), <?php echo $timeLeft; ?>);
</script>
<?php
}
?>
Try this
function Timer(container, timeLeft) {
// get hour, minute and second element using jQuery selector
var daysContainer = $(container).find('.day');
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);
var wholeDays = parseInt(wholeHours / 24,10);
//calculate hours left
var hours = parseInt(wholeHours % 24,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
$(daysContainer).text((wholeDays < 10 ? "0" : "") + wholeDays + (wholeDays <=0 ? " day" : " days"));
$(hoursContainer).text((hours < 10 ? "0" : "") + hours + (hours <=0 ? " hr" : " hrs"));
$(minsContainer).text((minutes < 10 ? "0" : "") + minutes + (minutes <=0 ? " min" : " mins"));
$(secsContainer).text((seconds < 10 ? "0" : "") + seconds + (seconds <=0 ? " sec" : " secs"));
}
}
}
Add days container on your loop
<div class="counter <?php echo $counterName; ?>">
<span class="day">00</span>
<span class="hour">00</span>
<span class="min">00</span>
<span class="sec">00</span>
</div>
Fiddle: https://jsfiddle.net/otezz/68d9yb6v/1/

JQuery UI Slider shows up on one page but not on other although almost similar code

Ok this is really driving me crazy. Here is a working example of what i am trying to achieve:
http://www.rockaholics-cologne.de/root/testslidenew.php
However in my other php script where i have exactly the same css and js libraries included and basically the same code for the funtcion of the slider except that the values are different the slider doesnt display:
<tbody>
<?php
include_once("php_includes/db_conx.php");
$sql = "SELECT TIME_TO_SEC(starttime), TIME_TO_SEC(endtime), date FROM wishtimes WHERE date BETWEEN '$startDate' AND '$endDate' ORDER BY date";
$query = mysqli_query($db_conx, $sql);
$wishtimes = array();
while($row = mysqli_fetch_assoc($query)) {
$weekday = date('l', strtotime($row['date']));
$wishtimes[$weekday] = $row;
}
$dates = date_range($startDate, $endDate);
print_r ($wishtimes);
print_r($dates);
$weekdays = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");
for($i=0; $i < count($weekdays); $i++) {
?>
<tr>
<td><?php echo $weekdays[$i]?></td>
<?php
if (isset($wishtimes[$weekdays[$i]])) {
?>
<td colspan="25">TEST<div id="slider<?php echo $i?>"></div></td>
<script>
$(function() {
var start = "<?php echo $wishtimes[$weekdays[$i]]['TIME_TO_SEC(starttime)']?>";
var end = "<?php echo $wishtimes[$weekdays[$i]]['TIME_TO_SEC(endtime)']?>";
start = start / 60;
end = end / 60;
$("#slider<?php echo $i?>").slider({
range: true,
min: 0,
max: 1440, /* Hour * 60 from 0:00 to 24:00 */
step: 15,
values: [ start, end ],
slide: function(e, ui) {
var hours = Math.floor(ui.value / 60);
var minutes = ui.value - (hours * 60);
if(hours.length == 1) hours = '0' + hours;
if(minutes.length == 1) minutes = '0' + minutes;
$('#something').html(hours+':'+minutes);
}
});
});
</script>
<td>
<a href><i class="icon-minus-sign"></i></a>
</td>
<?php
} else {
?>
<td colspan="25">
<script type="text/javascript">
function toggle(id) {
if ($('#'+id).is(":hidden")) {
$('#'+id).slideDown("fast");
} else {
$('#'+id).slideUp("fast");
}
}
</script>
<button id="addwishtime" onclick="toggle('<?php echo $i?>')">Add</button></br>
<div id="<?php echo $i?>" style="display: none;">
<?php
/* --- select FIRM of the current user ---
$sql = "SELECT firm FROM team WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
while ($row = mysql_fetch_array($query)) {
$firmname = $row[0];
} */
$sql = "SELECT starttime, endtime, shiftname, firm FROM shifts WHERE firm='TestBusiness' ORDER BY starttime ASC";
$query = mysqli_query($db_conx, $sql);
while($shifts = mysqli_fetch_array($query)) {
?>
<form method="post" action="">
<input type="hidden" value="<?php echo $dates[$i]?>" name="date">
<?php echo $dates[$i]?>
<input type="hidden" value="<?php echo $shifts['firm']?>" name="firm">
<?php echo $shifts['firm']?>
<input type="hidden" value="<?php echo $shifts['starttime']?>" name="starttime">
<?php echo $shifts['starttime']?>
<input type="hidden" value="<?php echo $shifts['endtime']?>" name="endtime">
<input type="submit" value="<b><?php echo $shifts['shiftname']?></b> Start: <?php echo $shifts['start']?> End: <?php echo $shifts['end']?>">
</form>
<?php
}
?>
</div>
</td>
</tr>
<?php
}
}
?>
</tbody>
The "TEST" gets printed out but no slider. If i look into F12 on Chrome i can see that values are set for start and end. The slider div also gets created but is simply at a height of 0px
What am i missing here??
EDIT
I just removed this script from datepicker which is also on the same page and as soon as i do it shows the slider but how can i get both to work???
<script>
$(function() {
var startDay;
var endDay;
var selectCurrentWeek = function() {
window.setTimeout(function () {
$('.week-picker').find('.ui-datepicker-current-day a').addClass('ui-state-active')
}, 1);
}
$('.week-picker').datepicker( {
dateFormat: 'yy-mm-dd',
firstDay: 1,
showOtherMonths: true,
selectOtherMonths: true,
onSelect: function(dateText, inst) {
var date = $(this).datepicker('getDate');
startDay = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() +1);
endDay = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 7);
var startDate = date.getFullYear() + "-" + (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() +1)) + "-" + ((date.getDate() - date.getDay() +1) < 10 ? '0' + (date.getDate() - date.getDay() +1) : (date.getDate() - date.getDay() +1));
var endDate = date.getFullYear() + "-" + (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1)) + "-" + ((date.getDate() - date.getDay() +7) < 10 ? '0' + (date.getDate() - date.getDay() +7) : (date.getDate() - date.getDay() +7));
window.location.href = "?startDate=" + startDate + "&endDate=" + endDate;
selectCurrentWeek();
},
beforeShowDay: function(date) {
var cssClass = '';
if(date >= startDay && date <= endDay)
cssClass = 'ui-datepicker-current-day';
return [true, cssClass];
},
onChangeMonthYear: function(year, month, inst) {
selectCurrentWeek();
}
});
$('.week-picker .ui-datepicker-calendar tr').live('mousemove', function() { $(this).find('td a').addClass('ui-state-hover'); });
$('.week-picker .ui-datepicker-calendar tr').live('mouseleave', function() { $(this).find('td a').removeClass('ui-state-hover'); });
});
</script>
I hope the problem should be , you are setting the range values as string but number or integer type required.please convert the string to number by using the following method or use your own method to convert.
start = parseInt(start); end = parseInt(end);
try this, i hope you will get answer. thank you.

How to add day on this js time script?

This is my js/php displaying function:
<script type="text/javascript">
$.fn.cycle.defaults.speed = 900;
$.fn.cycle.defaults.timeout = 5000;
$(function()
{
$('#demos pre code').each(function()
{
eval($(this).text());
});
$('#demos2 pre code').each(function()
{
eval($(this).text());
});
});
$(function($) {
var pstOptions = {
timeNotation: '12h',
am_pm: true,
utc: true,
utc_offset: <%SETTING_TIMEOFFSET%>,
fontFamily: 'Verdana, Times New Roman',
fontSize: '11px',
foreground: 'white',
background: 'black'
}
$('.jclockPST').jclock(pstOptions);
});
</script>
and this is my full js script:
/*
* jQuery jclock - Clock plugin - v 0.2.1
* http://plugins.jquery.com/project/jclock
*
* Copyright (c) 2007-2008 Doug Sparling <http://www.dougsparling.com>
* Licensed under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*/
(function($) {
$.fn.jclock = function(options) {
var version = '0.2.1';
// options
var opts = $.extend({}, $.fn.jclock.defaults, options);
return this.each(function() {
$this = $(this);
$this.timerID = null;
$this.running = false;
$.fn.jclock.getServerOffset($this);
var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
$this.timeNotation = o.timeNotation;
$this.am_pm = o.am_pm;
$this.utc = o.utc;
$this.utc_offset = o.utc_offset;
$this.css({
fontFamily: o.fontFamily,
fontSize: o.fontSize,
backgroundColor: o.background,
color: o.foreground
});
$.fn.jclock.startClock($this);
});
};
$.fn.jclock.getServerOffset = function(el) {
//Want to make a synchronous call to the server to get the server time.
$.ajax({
url: "Time.php",
async: false,
context: el,
success: function(result) {
var serverDate = new Date(+(result) * 1000); //Convert the seconds to a number, and multiple by 1000 to get milliseconds.
var clientDate = new Date();
$this = $(this.context[0]);
$this.serverOffset = clientDate - serverDate; //Set the offset between server and client.
}
});
};
$.fn.jclock.startClock = function(el) {
$.fn.jclock.stopClock(el);
$.fn.jclock.displayTime(el);
};
$.fn.jclock.stopClock = function(el) {
if(el.running) {
clearTimeout(el.timerID);
}
el.running = false;
};
$.fn.jclock.displayTime = function(el) {
var time = $.fn.jclock.getTime(el);
el.html(time);
el.timerID = setTimeout(function(){$.fn.jclock.displayTime(el)},1000);
};
$.fn.jclock.getTime = function(el) {
var now = new Date(new Date().getTime() - el.serverOffset); //Apply the server offset.
var hours, minutes, seconds;
if(el.utc == true) {
if(el.utc_offset != 0) {
now.setUTCHours(now.getUTCHours()+el.utc_offset);
}
hours = now.getUTCHours();
minutes = now.getUTCMinutes();
seconds = now.getUTCSeconds();
} else {
hours = now.getHours();
minutes = now.getMinutes();
seconds = now.getSeconds();
}
var am_pm_text = '';
(hours >= 12) ? am_pm_text = " P.M." : am_pm_text = " A.M.";
if (el.timeNotation == '12h') {
hours = ((hours > 12) ? hours - 12 : hours);
} else {
hours = ((hours < 10) ? "0" : "") + hours;
}
minutes = ((minutes < 10) ? "0" : "") + minutes;
seconds = ((seconds < 10) ? "0" : "") + seconds;
var timeNow = hours + ":" + minutes + ":" + seconds;
if ( (el.timeNotation == '12h') && (el.am_pm == true) ) {
timeNow += am_pm_text;
}
return timeNow;
};
// plugin defaults
$.fn.jclock.defaults = {
timeNotation: '24h',
am_pm: false,
utc: false,
fontFamily: '',
fontSize: '',
foreground: '',
background: '',
utc_offset: 0
};
})(jQuery);
How to add Date on it, so it will display Monday, Tuesday and etc ?
My current time is obtained via time.php via echo time();
Thanks a lot, It will be appreciated.
You can use the Date object's getDay() method to achieve this. getDay() method return 0 ( Sunday ) to 6 ( Saturday ).
You need to build an array first:
var wdays = [ 'Sunday', 'Monday', ... , 'Saturday'] ;
Then get the week day name by :
var weekday = wdays[now.getDay()];
timeNow += weekday; //append week day to the final result
function day() {
var days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
var now = new Date();
return days[now.getDay()];
}
now you can call the day function to get date in string var today = day() // 'Tue' or current day

Function to stop this Javascript timer

I'm new to Javascript, I got this Javascript timer from the net. I'm trying to stop the timer and insert the stopped time into the database if a certain PHP variable is set, but I'm not sure how to stop the timer. Here's the code. I saw this post and sadly, I still can't get it to work. How to stop a timer function from running?
Thanks!
<script type="text/javascript">
/**********************************************************************************************
* CountUp script by Praveen Lobo (http://PraveenLobo.com/techblog/javascript-countup-timer/)
* This notice MUST stay intact(in both JS file and SCRIPT tag) for legal use.
* http://praveenlobo.com/blog/disclaimer/
**********************************************************************************************/
function CountUp(initDate, id){
this.beginDate = new Date(initDate);
this.countainer = document.getElementById(id);
this.numOfDays = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
this.borrowed = 0, this.years = 0, this.months = 0, this.days = 0;
this.hours = 0, this.minutes = 0, this.seconds = 0;
this.updateNumOfDays();
this.updateCounter();
}
CountUp.prototype.updateNumOfDays=function(){
var dateNow = new Date();
var currYear = dateNow.getFullYear();
if ( (currYear % 4 == 0 && currYear % 100 != 0 ) || currYear % 400 == 0 ) {
this.numOfDays[1] = 29;
}
var self = this;
setTimeout(function(){self.updateNumOfDays();}, (new Date((currYear+1), 1, 2) - dateNow));
}
CountUp.prototype.datePartDiff=function(then, now, MAX){
var diff = now - then - this.borrowed;
this.borrowed = 0;
if ( diff > -1 ) return diff;
this.borrowed = 1;
return (MAX + diff);
}
CountUp.prototype.calculate=function(){
var currDate = new Date();
var prevDate = this.beginDate;
this.seconds = this.datePartDiff(prevDate.getSeconds(), currDate.getSeconds(), 60);
this.minutes = this.datePartDiff(prevDate.getMinutes(), currDate.getMinutes(), 60);
this.hours = this.datePartDiff(prevDate.getHours(), currDate.getHours(), 24);
this.days = this.datePartDiff(prevDate.getDate(), currDate.getDate(), this.numOfDays[currDate.getMonth()]);
this.months = this.datePartDiff(prevDate.getMonth(), currDate.getMonth(), 12);
this.years = this.datePartDiff(prevDate.getFullYear(), currDate.getFullYear(),0);
}
CountUp.prototype.addLeadingZero=function(value){
return value < 10 ? ("0" + value) : value;
}
CountUp.prototype.formatTime=function(){
this.seconds = this.addLeadingZero(this.seconds);
this.minutes = this.addLeadingZero(this.minutes);
this.hours = this.addLeadingZero(this.hours);
}
CountUp.prototype.updateCounter=function(){
this.calculate();
this.formatTime();
this.countainer.innerHTML =
" <strong>" + this.hours + "</strong> <small>" + (this.hours == 1? ":" : ":") + "</small>" +
" <strong>" + this.minutes + "</strong> <small>" + (this.minutes == 1? ":" : ":") + "</small>" +
" <strong>" + this.seconds + "</strong> <small>" + "</small>";
var self = this;
setTimeout(function(){self.updateCounter();}, 1000);
}
<?php if(isset($results['calltime'])) {$timevar= date("M d, Y H:i:s",strtotime($results['calltime']));}?>
window.onload=function(){ new CountUp('<?php echo $timevar; ?>', 'counter'); }
//I need a function to stop timer if (isset($results['firstcall_time']))
</script>
In your method updateCounter() You have following statement
setTimeout(function(){self.updateCounter();}, 1000);
make it like following first.
myTimer = setTimeout(function(){self.updateCounter();}, 1000);
and then whenever you want to stop the timer call this method.
clearTimeout(myTimer);
and then record the time.
It uses setTimeout for counting so you have to use clearTimeout for stopping the contdown.
reffer Clear Timeout
Cheers
In the lines:
setTimeout(function(){self.updateNumOfDays();}, (new Date((currYear+1), 1, 2) - dateNow));
And
setTimeout(function(){self.updateCounter();}, 1000);
You can see the recursion is being used, thus the timer keeps running.
So when you want to stop the timer do SOMETHING like this:
var flag = true;
<?php if (isset($results['firstcall_time'])){ ?>
flag = false;
<?php } ?>
And modify your script a little bit as:
setTimeout(function(){if(flag){self.updateNumOfDays();}else{//write code to cleartimeout}}, (new Date((currYear+1), 1, 2) - dateNow));//check for the flag before recursion
And
setTimeout(function(){if(flag){self.updateCounter();}}else{//write code to cleartimeout}, 1000);
He isn't using a timer. He is using setTimeout, but the executing function, is the same method, sort-of like recursion (but strictly speaking, it isn't). So, it's on going. Hope this makes sense.
A timer is implemented like:
// Start
var timerId = setInterval(func() {
// your code to execute
}, 5000);
// Stop
clearInterval(timerId);
I've added a stop method to CountUp. So you should now be able to do this:
// Start
var counter = new CountUp(new Date(), 'div');
// Stop
counter.stop();
Here's the code. I've just hand coded in here, so if there are any typos or something doesn't work then post a comment.
function CountUp(initDate, id){
this.beginDate = new Date(initDate);
this.countainer = document.getElementById(id);
this.numOfDays = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
this.borrowed = 0, this.years = 0, this.months = 0, this.days = 0;
this.hours = 0, this.minutes = 0, this.seconds = 0;
this.daysTimerId = setInterval(this.updateNumOfDays(), this.getDaysTimerInterval());
this.updateTimerId = setInterval(this.updateCounter(), 1000);
}
CountUp.prototype.stop=function(){
clearInterval(this.daysTimerId);
clearInterval(this.updateTimerId);
}
CountUp.prototype.getDaysTimerInterval=function(dt){
var dateNow = dt || new Date();
return (new Date((dateNow.getFullYear()+1), 1, 2) - dateNow));
}
CountUp.prototype.updateNumOfDays=function(){
var dateNow = new Date();
var currYear = dateNow.getFullYear();
if ( (currYear % 4 == 0 && currYear % 100 != 0 ) || currYear % 400 == 0 ) {
this.numOfDays[1] = 29;
}
// var self = this;
// setTimeout(function(){self.updateNumOfDays();}, self.getDaysTimerInterval(dateNow));
}
CountUp.prototype.datePartDiff=function(then, now, MAX){
var diff = now - then - this.borrowed;
this.borrowed = 0;
if ( diff > -1 ) return diff;
this.borrowed = 1;
return (MAX + diff);
}
CountUp.prototype.calculate=function(){
var currDate = new Date();
var prevDate = this.beginDate;
this.seconds = this.datePartDiff(prevDate.getSeconds(), currDate.getSeconds(), 60);
this.minutes = this.datePartDiff(prevDate.getMinutes(), currDate.getMinutes(), 60);
this.hours = this.datePartDiff(prevDate.getHours(), currDate.getHours(), 24);
this.days = this.datePartDiff(prevDate.getDate(), currDate.getDate(), this.numOfDays[currDate.getMonth()]);
this.months = this.datePartDiff(prevDate.getMonth(), currDate.getMonth(), 12);
this.years = this.datePartDiff(prevDate.getFullYear(), currDate.getFullYear(),0);
}
CountUp.prototype.addLeadingZero=function(value){
return value < 10 ? ("0" + value) : value;
}
CountUp.prototype.formatTime=function(){
this.seconds = this.addLeadingZero(this.seconds);
this.minutes = this.addLeadingZero(this.minutes);
this.hours = this.addLeadingZero(this.hours);
}
CountUp.prototype.updateCounter=function(){
this.calculate();
this.formatTime();
this.countainer.innerHTML =
" <strong>" + this.hours + "</strong> <small>" + (this.hours == 1? ":" : ":") + "</small>" +
" <strong>" + this.minutes + "</strong> <small>" + (this.minutes == 1? ":" : ":") + "</small>" +
" <strong>" + this.seconds + "</strong> <small>" + "</small>";
// var self = this;
// setTimeout(function(){self.updateCounter();}, 1000);
}
Here is how I stopped the counter:
I inserted this few lines before "CountUp.prototype.updateCounter=function(){"
var today=new Date();
var start=new Date(2013,10,25,5,35,0); //example: Stop date
diff = start-today;
Then, inside updateCounter function, instead of directly call the setTimeout I added a condition:
if ( ( (this.seconds==0) && (this.minutes==0) (this.hours==0) && (this.days==0) ) || (diff <=0) ) { //on the fly (page is laready open with the counter running) or onload
//Time's up!
} else {
setTimeout(function(){self.updateCounter();}, 1000);
}
So the new code will look like this:
var today=new Date();
var start=new Date(2013,10,25,5,35,0);
diff = start-today;
Counter.prototype.updateCounter=function(){
this.calculate();
this.formatTime();
this.countainer.innerHTML = " <strong>" + this.seconds + "</strong> " + (this.seconds == 1? ":" : ":")+
" <strong>" + this.minutes + "</strong> " + (this.minutes == 1? ":" : ":")+
" <strong>" + this.hours + "</strong> " + (this.hours == 1? ":" : ":")+
" <strong>" + this.days + "</strong> " + (this.days == 1? ":" : "");
var self = this;
if ( ( (this.seconds==0) && (this.minutes==0) (this.hours==0) && (this.days==0) ) || (diff <=0) ) { //on the fly or onload
//Time's up!
} else {
setTimeout(function(){self.updateCounter();}, 1000);
}
}
Hope that will help.
Shams

Capture javascript stopwatch stop time and store it as php variable

I'm using this stopwatch:
<script language="JavaScript" type="text/javascript">
window.onload = function()
{
stopwatch('Start');
}
<!--
var sec = 0;
var min = 0;
var hour = 0;
function stopwatch(text) {
sec++;
if (sec == 60) {
sec = 0;
min = min + 1; }
else {
min = min; }
if (min == 60) {
min = 0;
hour += 1; }
if (sec<=9) { sec = "0" + sec; }
document.clock.stwa.value = ((hour<=9) ? "0"+hour : hour) + " : " + ((min<=9) ? "0" + min : min) + " : " + sec;
if (text == "Start") { document.clock.theButton.value = "Stop "; }
if (text == "Stop ") { document.clock.theButton.value = "Start"; }
if (document.clock.theButton.value == "Start") {
window.clearTimeout(SD);
return true; }
SD=window.setTimeout("stopwatch();", 1000);
}
function resetIt() {
sec = -1;
min = 0;
hour = 0;
if (document.clock.theButton.value == "Stop ") {
document.clock.theButton.value = "Start"; }
window.clearTimeout(SD);
}
// -->
</script>
and would like to capture the time that the clock is stopped on, and then store it as a PHP variable so that I can insert it into our database along with a load of other PHP variables. Is this possible?
Thanks for any help
Spice up your code with some AJAX. Inside of function resetIt() pass the current timestamp to your php script.
jQuery has a solid AJAX part and nice documentation with examples too.
(Assuming jQuery loaded, up and running)
function resetIt() {
$.ajax({
url: 'your.php',
success: function(response){
alert(response);
}
});
sec = -1;
min = 0;
hour = 0;
if (document.clock.theButton.value == "Stop ") {
document.clock.theButton.value = "Start"; }
window.clearTimeout(SD);
}
your.php (since all you need to save the actual timestamp we won't pass any variable to the PHP part. If you need to add specific variables (from JS) you can add them, of course)
if(mysql_query("INSERT INTO `database` (`stopped`) VALUES (NOW())")) {
echo 'success';
} else {
echo 'failed';
}
die();

Categories