Jquery countdown counter not working properly - javascript

Am creating a coming soon website
<div class="countdown styled"></div>
From this div, I need a countdown timer. So I used the default countdown timer from jquery.countdown.js.
UI coming correctly and shows seconds at 0 only.
What do I have to do to run a counter?
Am getting Js code at jquery.countdown.js file
(function() {
(function($) {
$.countdown = function(el, options) {
var getDateData,
_this = this;
this.el = el;
this.$el = $(el);
this.$el.data("countdown", this);
this.init = function() {
_this.options = $.extend({}, $.countdown.defaultOptions, options);
if (_this.options.refresh) {
_this.interval = setInterval(function() {
return _this.render();
}, _this.options.refresh);
}
_this.render();
return _this;
};
getDateData = function(endDate) {
var dateData, diff;
endDate = Date.parse($.isPlainObject(_this.options.date) ? _this.options.date : new Date(_this.options.date));
diff = (endDate - Date.parse(new Date)) / 1000;
if (diff <= 0) {
diff = 0;
if (_this.interval) {
_this.stop();
}
_this.options.onEnd.apply(_this);
}
dateData = {
years: 0,
days: 10,
hours: 10,
min: 20,
sec: 14,
millisec: 10
};
$.countdown.defaultOptions = {
date: "Dec 25, 2021 15:03:25",
refresh: 1000,
onEnd: $.noop,
render: function(date) {
return $(this.el).html("" + date.years + " years, " + date.days + " days, " + (this.leadingZeros(date.hours)) + " hours, " + (this.leadingZeros(date.min)) + " min and " + (this.leadingZeros(date.sec)) + " sec");
}
};
$.fn.countdown = function(options) {
return $.each(this, function(i, el) {
var $el;
$el = $(el);
if (!$el.data('countdown')) {
return $el.data('countdown', new $.countdown(el, options));
}
});
};
return void 0;
})(jQuery);
}).call(this);
But counter not running . Only UI coming . Thanks in advance

Related

Getting javascript - Uncaught TypeError: Issue

I am using numscroller.js for a counter but I'm getting two javascript errors:
Uncaught TypeError: Cannot read property 'top' of undefined at HTMLHeadingElement. - Line no - 40.
Can anyone help me please with the below code. It's showing the error is in the line number 40. Any help would be appreciated. Thank you in advance.
working URL - http://bluecrystaluae.com/counter/counter.html
jQuery.noConflict();
(function($) {
$(window).on("load", function() {
$(document).scrollzipInit();
$(document).rollerInit();
});
$(window).on("load scroll resize", function() {
$('.numscroller').scrollzip({
showFunction: function() {
numberRoller($(this).attr('data-slno'));
},
wholeVisible: false,
});
});
$.fn.scrollzipInit = function() {
$('body').prepend("<div style='position:fixed;top:0px;left:0px;width:0;height:0;' id='scrollzipPoint'></div>");
};
$.fn.rollerInit = function() {
var i = 0;
$('.numscroller').each(function() {
i++;
$(this).attr('data-slno', i);
$(this).addClass("roller-title-number-" + i);
});
};
$.fn.scrollzip = function(options) {
var settings = $.extend({
showFunction: null,
hideFunction: null,
showShift: 0,
wholeVisible: false,
hideShift: 0,
}, options);
return this.each(function(i, obj) {
$(this).addClass('scrollzip');
if ($.isFunction(settings.showFunction)) {
if (!$(this).hasClass('isShown') &&
($(window).outerHeight() + $('#scrollzipPoint').offset().top - settings.showShift) > ($(this).offset().top + ((settings.wholeVisible) ? $(this).outerHeight() : 0)) &&
($('#scrollzipPoint').offset().top + ((settings.wholeVisible) ? $(this).outerHeight() : 0)) < ($(this).outerHeight() + $(this).offset().top - settings.showShift)
) {
$(this).addClass('isShown');
settings.showFunction.call(this);
}
}
if ($.isFunction(settings.hideFunction)) {
if (
$(this).hasClass('isShown') &&
(($(window).outerHeight() + $('#scrollzipPoint').offset().top - settings.hideShift) < ($(this).offset().top + ((settings.wholeVisible) ? $(this).outerHeight() : 0)) ||
($('#scrollzipPoint').offset().top + ((settings.wholeVisible) ? $(this).outerHeight() : 0)) > ($(this).outerHeight() + $(this).offset().top - settings.hideShift))
) {
$(this).removeClass('isShown');
settings.hideFunction.call(this);
}
}
return this;
});
};
function numberRoller(slno) {
var min = $('.roller-title-number-' + slno).attr('data-min');
var max = $('.roller-title-number-' + slno).attr('data-max');
var timediff = $('.roller-title-number-' + slno).attr('data-delay');
var increment = $('.roller-title-number-' + slno).attr('data-increment');
var numdiff = max - min;
var timeout = (timediff * 1000) / numdiff;
//if(numinc<10){
//increment=Math.floor((timediff*1000)/10);
//}//alert(increment);
numberRoll(slno, min, max, increment, timeout);
}
function numberRoll(slno, min, max, increment, timeout) { //alert(slno+"="+min+"="+max+"="+increment+"="+timeout);
if (min <= max) {
$('.roller-title-number-' + slno).html(min);
min = parseInt(min) + parseInt(increment);
setTimeout(function() {
numberRoll(eval(slno), eval(min), eval(max), eval(increment), eval(timeout))
}, timeout);
} else {
$('.roller-title-number-' + slno).html(max);
}
}
})(jQuery);
I think you forgot to return your jquery element in your plugin functions
$.fn.scrollzipInit = function() {
return $('body').prepend("<div style='position:fixed;top:0px;left:0px;width:0;height:0;' id='scrollzipPoint'></div>");
};
And
$.fn.rollerInit = function() {
var i = 0;
return $('.numscroller').each(function() {
i++;
$(this).attr('data-slno', i);
$(this).addClass("roller-title-number-" + i);
});
};

Javascript not able to make common functions for a prototype

I am trying to make timer in javascript using a prototype. Each time a new timer is created, a object of prototype is created. There are methods to increase time and print each second. The whole code snippet is as follows:
function Timer(elem) {
this.interval = null;
this.currentTime = {
sec: 0,
min: 0,
hr: 0
};
this.elem = elem;
};
Timer.prototype.start = function() {
var self = this;
if (!self.interval) {
self.interval = setInterval(update, 1000);
}
function update() {
incrementTime();
render();
}
function render() {
self.elem.innerText = getPrintableTime();
}
function incrementTime() {
self.currentTime["min"] += Math.floor((++self.currentTime["sec"]) / 60);
self.currentTime["hr"] += Math.floor(self.currentTime["min"] / 60);
self.currentTime["sec"] = self.currentTime["sec"] % 60;
self.currentTime["min"] = self.currentTime["min"] % 60;
}
function getPrintableTime() {
var text = getTwoDigitNumber(self.currentTime["hr"]) + ":" + getTwoDigitNumber(self.currentTime["min"]) + ":" + getTwoDigitNumber(self.currentTime["sec"]);
return text;
}
function getTwoDigitNumber(number) {
if (number > 9) {
return "" + number;
} else {
return "0" + number;
}
}
};
module.exports = Timer;
I have all methods in start function. The problem is that for each new object of Timer, new space for each method will be used which is very inefficient. But when I try to put methods outside of start function, they lose access to self variable. You can see that there is setInterval function used which will be calling these methods per second. I cannot use this also as this will be instance of Window in subsequent calls.
How can I solve this situation by only keeping one instance of all the interior methods?
You don't need to have all methods in the start function. Yes, for each new Timer instance, new space for each function will be used, but that is necessary when you want to work with setInterval as you need a function which closes over the instance. However, you need only one such closure, the other methods can be standard prototype methods.
function getTwoDigitNumber(number) {
return (number > 9 ? "" : "0") + number;
}
function Timer(elem) {
this.interval = null;
this.currentTime = {
sec: 0,
min: 0,
hr: 0
};
this.elem = elem;
};
Timer.prototype.start = function() {
var self = this;
if (!this.interval) {
this.interval = setInterval(function update() {
self.incrementTime();
self.render();
}, 1000);
}
};
Timer.prototype.render() {
this.elem.innerText = this.getPrintableTime();
};
Timer.prototype.incrementTime = function() {
this.currentTime.sec += 1;
this.currentTime.min += Math.floor(this.currentTime.sec / 60);
this.currentTime.hr += Math.floor(this.currentTime.min / 60);
this.currentTime.sec = this.currentTime.sec % 60;
this.currentTime.min = this.currentTime.min % 60;
};
Timer.prototype.getPrintableTime = function() {
var text = getTwoDigitNumber(this.currentTime.hr) + ":"
+ getTwoDigitNumber(this.currentTime.min) + ":"
+ getTwoDigitNumber(self.currentTime.sec);
return text;
};
module.exports = Timer;
Btw, regarding your incrementTime pattern, you should have a look at How to create an accurate timer in javascript?.
You can use apply to use functions defined outside of prototype with correct this context.
function Timer(elem) {
this.interval = null;
this.currentTime = {
sec: 0,
min: 0,
hr: 0
};
this.elem = elem;
};
function update() {
incrementTime.apply(this);
render.apply(this);
}
function render() {
this.elem.innerText = getPrintableTime.apply(this);
}
function incrementTime() {
this.currentTime["min"] += Math.floor((++this.currentTime["sec"]) / 60);
this.currentTime["hr"] += Math.floor(this.currentTime["min"] / 60);
this.currentTime["sec"] = this.currentTime["sec"] % 60;
this.currentTime["min"] = this.currentTime["min"] % 60;
}
function getPrintableTime() {
var text = getTwoDigitNumber(this.currentTime["hr"]) + ":" + getTwoDigitNumber(this.currentTime["min"]) + ":" + getTwoDigitNumber(this.currentTime["sec"]);
return text;
}
function getTwoDigitNumber(number) {
if (number > 9) {
return "" + number;
} else {
return "0" + number;
}
}
Timer.prototype.start = function() {
var self = this;
if (!self.interval) {
self.interval = setInterval(function() {
update.apply(self);
}, 1000);
}
};
document.addEventListener('DOMContentLoaded', function() {
var timer = new Timer(document.getElementById('timer'));
timer.start();
}, false);
<div id="timer"></div>
If I understand correctly, you're wanting to only create one interval.
One possible solution would be to create a static method and variable to manage the setInterval. I would note that while this may be more performance friendly, the timers will always start and run on the same count...not from the moment each timer is created. (See example)
Of course, you could capture the current timestamp and calculate the elapsed time from there. But, that's another thread ;)
function Timer(elem) {
this.interval = null;
this.currentTime = {
sec: 0,
min: 0,
hr: 0
};
this.elem = elem;
};
Timer.subscribe = function(timer) {
Timer.subscribers = Timer.subscribers || [];
if (Timer.subscribers.indexOf(timer) === -1) {
Timer.subscribers.push(timer);
timer.update.call(timer);
}
Timer.checkInterval();
};
Timer.unsubscribe = function(timer) {
Timer.subscribers = Timer.subscribers || [];
if (Timer.subscribers.indexOf(timer) !== -1) {
Timer.subscribers.splice(Timer.subscribers.indexOf(timer), 1);
}
Timer.checkInterval();
};
Timer.checkInterval = function() {
if (!Timer.interval && Timer.subscribers.length > 0) {
Timer.interval = setInterval(function() {
Timer.subscribers.forEach(function(item) {
item.update.call(item);
});
}, 1000);
} else if (Timer.interval && Timer.subscribers.length === 0) {
clearInterval(Timer.interval);
Timer.interval = null;
}
};
Timer.prototype = {
start: function() {
Timer.subscribe(this);
},
stop: function() {
Timer.unsubscribe(this);
},
update: function() {
this.incrementTime();
this.render();
},
incrementTime: function() {
this.currentTime["min"] += Math.floor((++this.currentTime["sec"]) / 60);
this.currentTime["hr"] += Math.floor(this.currentTime["min"] / 60);
this.currentTime["sec"] = this.currentTime["sec"] % 60;
this.currentTime["min"] = this.currentTime["min"] % 60;
},
render: function() {
var self = this;
function getPrintableTime() {
var text = getTwoDigitNumber(self.currentTime["hr"]) + ":" + getTwoDigitNumber(self.currentTime["min"]) + ":" + getTwoDigitNumber(self.currentTime["sec"]);
return text;
}
function getTwoDigitNumber(number) {
if (number > 9) {
return "" + number;
} else {
return "0" + number;
}
}
this.elem.innerText = getPrintableTime();
}
};
/**
*
*/
var timers = document.getElementById('timers');
function addTimer() {
var el = document.createElement('div');
var tmr = document.createElement('span');
var btn = document.createElement('button');
var t = new Timer(tmr);
btn.innerText = 'Stop';
btn.onclick = function() {
t.stop();
};
el.appendChild(tmr);
el.appendChild(btn);
timers.appendChild(el);
t.start();
};
<div id="timers"></div>
<button onclick="addTimer()">Add Timer</button>

JavaScript countdown timer not working

I am a JavaScript newbie. I am using a template which has the code below. It shows a countdown timer. I can't understand why it does not work. I have provided it the value of 90 days. Please guide. Thanks
// Generated by CoffeeScript 1.4.0
/*
countdown is a simple jquery plugin for countdowns
Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
and GPL-3.0 (http://opensource.org/licenses/GPL-3.0) licenses.
#source: http://github.com/rendro/countdown/
#autor: Robert Fleischmann
#version: 1.0.1
*/
(function () {
(function ($) {
$.countdown = function (el, options) {
var getDateData,
_this = this;
this.el = el;
this.$el = $(el);
this.$el.data("countdown", this);
this.init = function () {
_this.options = $.extend({}, $.countdown.defaultOptions, options);
if (_this.options.refresh) {
_this.interval = setInterval(function () {
return _this.render();
}, _this.options.refresh);
}
_this.render();
return _this;
};
getDateData = function (endDate) {
var dateData, diff;
endDate = Date.parse($.isPlainObject(_this.options.date) ? _this.options.date : new Date(_this.options.date));
diff = (endDate - Date.parse(new Date)) / 1000;
if (diff <= 0) {
diff = 0;
if (_this.interval) {
_this.stop();
}
_this.options.onEnd.apply(_this);
}
dateData = {
years: 90,
days: 90,
hours: 0,
min: 0,
sec: 90,
millisec: 0
};
if (diff >= (365.25 * 86400)) {
dateData.years = Math.floor(diff / (365.25 * 86400));
diff -= dateData.years * 365.25 * 86400;
}
if (diff >= 86400) {
dateData.days = Math.floor(diff / 86400);
diff -= dateData.days * 86400;
}
if (diff >= 3600) {
dateData.hours = Math.floor(diff / 3600);
diff -= dateData.hours * 3600;
}
if (diff >= 60) {
dateData.min = Math.floor(diff / 60);
diff -= dateData.min * 60;
}
dateData.sec = diff;
return dateData;
};
this.leadingZeros = function (num, length) {
if (length == null) {
length = 2;
}
num = String(num);
while (num.length < length) {
num = "0" + num;
}
return num;
};
this.update = function (newDate) {
_this.options.date = newDate;
return _this;
};
this.render = function () {
_this.options.render.apply(_this, [getDateData(_this.options.date)]);
return _this;
};
this.stop = function () {
if (_this.interval) {
clearInterval(_this.interval);
}
_this.interval = null;
return _this;
};
this.start = function (refresh) {
if (refresh == null) {
refresh = _this.options.refresh || $.countdown.defaultOptions.refresh;
}
if (_this.interval) {
clearInterval(_this.interval);
}
_this.render();
_this.options.refresh = refresh;
_this.interval = setInterval(function () {
return _this.render();
}, _this.options.refresh);
return _this;
};
return this.init();
};
$.countdown.defaultOptions = {
date: "June 7, 2087 15:03:25",
refresh: 1000,
onEnd: $.noop,
render: function (date) {
return $(this.el).html("" + date.years + " years, " + date.days + " days, " + (this.leadingZeros(date.hours)) + " hours, " + (this.leadingZeros(date.min)) + " min and " + (this.leadingZeros(date.sec)) + " sec");
}
};
$.fn.countdown = function (options) {
return $.each(this, function (i, el) {
var $el;
$el = $(el);
if (!$el.data('countdown')) {
return $el.data('countdown', new $.countdown(el, options));
}
});
};
return void 0;
})(jQuery);
}).call(this);
Just change
endDate = Date.parse($.isPlainObject(_this.options.date)
? _this.options.date : new Date(_this.options.date));
to
endDate = Date.parse($.isPlainObject(_this.options.date)
? _this.options.date : new Date(year,month,date));
example:
endDate = Date.parse($.isPlainObject(_this.options.date)
? _this.options.date : new Date(2017,02,15));

How can I make my countdown reset every night at 16:00

I am working on a countdown for my website. We provide same day dispatch before 16:00 each day. I need a counter that will display a countdown to 16:00 each day.
Eventually, I will modify the code so that it doesn't display at all on the weekends but for now, all I need is something that can countdown everyday. Disappear after 16:00 and start fresh and countdown again from 00:00
Below is the code I have so far.
<?php
if (new DateTime() < new DateTime("16:00:00")) {
?>
<script type="text/javascript">
var CDown = function() {
this.state=0;// if initialized
this.counts=[];// array holding countdown date objects and id to print to {d:new Date(2013,11,18,18,54,36), id:"countbox1"}
this.interval=null;// setInterval object
}
CDown.prototype = {
init: function(){
this.state=1;
var self=this;
this.interval=window.setInterval(function(){self.tick();}, 1000);
},
add: function(date,id){
this.counts.push({d:date,id:id});
this.tick();
if(this.state==0) this.init();
},
expire: function(idxs){
for(var x in idxs) {
this.display(this.counts[idxs[x]], "Now!");
this.counts.splice(idxs[x], 1);
}
},
format: function(r){
var out="";
if(r.d != 0){out += r.d +" "+((r.d==1)?"day":"days")+", ";}
if(r.h != 0){out += r.h +" "+((r.h==1)?"hour":"hours")+", ";}
out += r.m +" "+((r.m==1)?"min":"mins")+", ";
out += r.s +" "+((r.s==1)?"sec":"secs")+", ";
return out.substr(0,out.length-2);
},
math: function(work){
var y=w=d=h=m=s=ms=0;
ms=(""+((work%1000)+1000)).substr(1,3);
work=Math.floor(work/1000);//kill the "milliseconds" so just secs
y=Math.floor(work/31536000);//years (no leapyear support)
w=Math.floor(work/604800);//weeks
d=Math.floor(work/86400);//days
work=work%86400;
h=Math.floor(work/3600);//hours
work=work%3600;
m=Math.floor(work/60);//minutes
work=work%60;
s=Math.floor(work);//seconds
return {y:y,w:w,d:d,h:h,m:m,s:s,ms:ms};
},
tick: function(){
var now=(new Date()).getTime(),
expired=[],cnt=0,amount=0;
if(this.counts)
for(var idx=0,n=this.counts.length; idx<n; ++idx){
cnt=this.counts[idx];
amount=cnt.d.getTime()-now;//calc milliseconds between dates
// if time is already past
if(amount<0){
expired.push(idx);
}
// date is still good
else{
this.display(cnt, this.format(this.math(amount)));
}
}
// deal with any expired
if(expired.length>0) this.expire(expired);
// if no active counts, stop updating
if(this.counts.length==0) window.clearTimeout(this.interval);
},
display: function(cnt,msg){
document.getElementById(cnt.id).innerHTML=msg;
}
};
window.onload=function(){
var cdown = new CDown();
cdown.add(new Date(2015,9,16,16,00,00), "countbox1");
};
</script>
<span style="font-size:30px;"><div id="countbox1"></div></span>
<?php } ?>
concept here testing
change the variable countDownTo to the current hour on line 8, 103 and 109
change the variable minute on line 133
<?php if (new DateTime() < new DateTime( "16:00:00")) { ?>
<script type="text/javascript">
var check = 0;
/*set the countdown hour*/
var countDownTo = 16;
var CDown = function() {
this.state = 0; // if initialized
this.counts = []; // array holding countdown date objects and id to print to {d:new Date(2013,11,18,18,54,36), id:"countbox1"}
this.interval = null; // setInterval object
}
CDown.prototype = {
init: function() {
this.state = 1;
var self = this;
this.interval = window.setInterval(function() {
self.tick();
}, 1000);
},
add: function(date, id) {
this.counts.push({
d: date,
id: id
});
this.tick();
if (this.state == 0) this.init();
},
expire: function(idxs) {
for (var x in idxs) {
this.display(this.counts[idxs[x]], "Now!");
this.counts.splice(idxs[x], 1);
}
},
format: function(r) {
var out = "";
if (r.d != 0) {
out += r.d + " " + ((r.d == 1) ? "day" : "days") + ", ";
}
if (r.h != 0) {
out += r.h + " " + ((r.h == 1) ? "hour" : "hours") + ", ";
}
out += r.m + " " + ((r.m == 1) ? "min" : "mins") + ", ";
out += r.s + " " + ((r.s == 1) ? "sec" : "secs") + ", ";
return out.substr(0, out.length - 2);
},
math: function(work) {
var y = w = d = h = m = s = ms = 0;
ms = ("" + ((work % 1000) + 1000)).substr(1, 3);
work = Math.floor(work / 1000); //kill the "milliseconds" so just secs
y = Math.floor(work / 31536000); //years (no leapyear support)
w = Math.floor(work / 604800); //weeks
d = Math.floor(work / 86400); //days
work = work % 86400;
h = Math.floor(work / 3600); //hours
work = work % 3600;
m = Math.floor(work / 60); //minutes
work = work % 60;
s = Math.floor(work); //seconds
return {
y: y,
w: w,
d: d,
h: h,
m: m,
s: s,
ms: ms
};
},
tick: function() {
var now = (new Date()).getTime(),
expired = [],
cnt = 0,
amount = 0;
if (this.counts)
for (var idx = 0, n = this.counts.length; idx < n; ++idx) {
cnt = this.counts[idx];
amount = cnt.d.getTime() - now; //calc milliseconds between dates
// if time is already past
if (amount < 0) {
expired.push(idx);
}
// date is still good
else {
this.display(cnt, this.format(this.math(amount)));
}
}
// deal with any expired
if (expired.length > 0) this.expire(expired);
// if no active counts, stop updating
if (this.counts.length == 0) window.clearTimeout(this.interval);
},
display: function(cnt, msg) {
if (msg == `Now!`) {
check = 1;
msg = ``;
var cdown = new CDown();
var currentdate = new Date();
var year = currentdate.getFullYear();
var month = currentdate.getMonth();
var day = currentdate.getDate() + 1;
var currenthour = currentdate.getHours();
/*perform check here*/
if (countDownTo == 16) {
countDownTo = 0;
} else {
countDownTo = 16;
}
var hour = countDownTo;
var minute = 0;
var second = 0;
cdown.add(new Date(year, month, day, hour, minute, second), "countbox1");
} else {
check = 0;
}
if (countDownTo == 0) msg = ``;
document.getElementById(cnt.id).innerHTML = msg;
}
};
window.onload = function() {
var cdown = new CDown();
var currentdate = new Date();
var year = currentdate.getFullYear();
var month = currentdate.getMonth();
var day = currentdate.getDate();
var hour = countDownTo;
var minute = 0;
var second = 0;
cdown.add(new Date(year, month, day, hour, minute, second), "countbox1");
};
</script>
<span style="font-size:30px;"><div id="countbox1"></div></span>
<?php } ?>
You can use a cron job that will reset a variable once every 24 hours.

Javascript clock that advances 1h at every button click

I'm creating a simple web browser game. In it there is a clock, it doesn't display the real time, but is supposed to start at 9:00 am and avance 1h every time a button is clicked. The problem is that it only works on the first button click and always stays at 10am when I click a button again. I don't understand why.
Here's the code:
<script role="script" id="twine-user-script" type="text/twine-javascript">
$(document).ready( function() {
var callback = function() {
displayTime.incrementTime();
};
$('#onebutton .link-internal').on('click', callback);
$('#container1 .link-internal').on('click', callback);
$('#container2 .link-internal').on('click', callback);
var displayTime = {
currentTime: new Date(new Date().getUTCFullYear(),
new Date().getUTCMonth(),
new Date().getUTCDay(),
'9',
'0',
'0',
'0'),
hoursVal: null,
hours: function() {
return displayTime.currentTime.getHours();
},
minutesVal: null,
minutes: function() {
return displayTime.currentTime.getMinutes();
},
meridiem: "am",
init: function() {
displayTime.formatDate();
displayTime.display();
},
formatDate: function() {
if (displayTime.hours() > 12) {
displayTime.hoursVal = displayTime.hours() - 12;
displayTime.meridiem = "pm";
}
if (displayTime.hours() === 0) {
displayTime.hoursVal = 12;
}
if(displayTime.hours() < 10) {
displayTime.hoursVal = "0" + displayTime.hours();
}
if(displayTime.minutes() < 10) {
displayTime.minutesVal = "0" + displayTime.minutes();
}
},
resetValues: function() {
displayTime.hoursVal = null;
displayTime.minutesVal = null;
//displayTime.secondsVal = null;
},
display: function() {
var clockDiv = document.getElementById('clock');
clockDiv.innerText = (displayTime.hoursVal === null ? displayTime.hours() : displayTime.hoursVal) + ":" +
(displayTime.minutesVal === null ? displayTime.minutes() : displayTime.minutesVal) + " " +
displayTime.meridiem;
},
incrementTime: function() {
displayTime.currentTime = new Date(displayTime.currentTime.getTime() + (1000 * 60 * 60));
displayTime.resetValues();
displayTime.formatDate();
displayTime.display();
}
};
displayTime.init();
setInterval(displayTime.init, 1000);
});
</script>
Can anyone point out where the error in my code is?
This JSFiddle works better, but I need your HTML too to give you the exact problem you have:
JS:
$(document).ready(function () {
var callback = function () {
displayTime.incrementTime();
};
$('#onebutton').on('click', callback);
$('#container1').on('click', callback);
$('#container2').on('click', callback);
var displayTime = {
currentTime: new Date(new Date().getUTCFullYear(),
new Date().getUTCMonth(),
new Date().getUTCDay(),
'9',
'0',
'0',
'0'),
hoursVal: null,
hours: function () {
return displayTime.currentTime.getHours();
},
minutesVal: null,
minutes: function () {
return displayTime.currentTime.getMinutes();
},
meridiem: "am",
init: function () {
displayTime.formatDate();
displayTime.display();
},
formatDate: function () {
if (displayTime.hours() > 12) {
displayTime.hoursVal = displayTime.hours() - 12;
displayTime.meridiem = "pm";
}
if (displayTime.hours() === 0) {
displayTime.hoursVal = 12;
}
if (displayTime.hours() < 10) {
displayTime.hoursVal = "0" + displayTime.hours();
}
if (displayTime.minutes() < 10) {
displayTime.minutesVal = "0" + displayTime.minutes();
}
},
resetValues: function () {
displayTime.hoursVal = null;
displayTime.minutesVal = null;
//displayTime.secondsVal = null;
},
display: function () {
var clockDiv = document.getElementById('clock');
clockDiv.innerText = (displayTime.hoursVal === null ? displayTime.hours() : displayTime.hoursVal) + ":" + (displayTime.minutesVal === null ? displayTime.minutes() : displayTime.minutesVal) + " " + displayTime.meridiem;
},
incrementTime: function () {
displayTime.currentTime = new Date(displayTime.currentTime.getTime() + (1000 * 60 * 60));
displayTime.resetValues();
displayTime.formatDate();
displayTime.display();
}
};
displayTime.init();
setInterval(displayTime.init, 1000);
});

Categories

Resources