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
Related
I am trying to pass time in microseconds from my PHP server to this Hilios countdown code. Well, it's passing and calculating correctly, but the countdown is static, I need it to keep updating until it resets:
01 days 00:00:10 (09, 08, ..., 00:00:00)
Any idea what I can do to keep the countdown updated, I tried setTimeout and interval, but to no avail. Thanks !!!
<html>
<head>
<script src="//code.jquery.com/jquery.js"></script>
<!--<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment-with-locales.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.4.0/moment-timezone-with-data-2010-2020.min.js"></script>
<!-- Include MomentJS library -->
<?php
setlocale(LC_TIME, 'pt_BR', 'pt_BR.utf-8', 'pt_BR.utf-8', 'portuguese');
date_default_timezone_set('America/Sao_Paulo');
echo '<b>ServerTime</b> = '.date('D M d Y H:i:s').' GMT-0300 (Horário Padrão de Brasília)';
?>
<br><br>
<script>
function horaServer(){
return '<?php echo round(microtime(true) * 1000);?>';
}
(function(factory) {
"use strict";
if (typeof define === "function" && define.amd) {
define([ "jquery" ], factory);
} else {
factory(jQuery);
}
})(function($) {
"use strict";
var PRECISION = 100;
var instances = [], matchers = [];
matchers.push(/^[0-9]*$/.source);
matchers.push(/([0-9]{1,2}\/){2}[0-9]{4}( [0-9]{1,2}(:[0-9]{2}){2})?/.source);
matchers.push(/[0-9]{4}([\/\-][0-9]{1,2}){2}( [0-9]{1,2}(:[0-9]{2}){2})?/.source);
matchers = new RegExp(matchers.join("|"));
function parseDateString(dateString) {
if (dateString instanceof Date) {
return dateString;
}
if (String(dateString).match(matchers)) {
if (String(dateString).match(/^[0-9]*$/)) {
dateString = Number(dateString);
}
if (String(dateString).match(/\-/)) {
dateString = String(dateString).replace(/\-/g, "/");
}
return new Date(dateString);
} else {
throw new Error("Couldn't cast `" + dateString + "` to a date object.");
}
}
var DIRECTIVE_KEY_MAP = {
Y: "years",
m: "months",
w: "weeks",
d: "days",
D: "totalDays",
H: "hours",
M: "minutes",
S: "seconds"
};
function strftime(offsetObject) {
return function(format) {
var directives = format.match(/%(-|!)?[A-Z]{1}(:[^;]+;)?/gi);
if (directives) {
for (var i = 0, len = directives.length; i < len; ++i) {
var directive = directives[i].match(/%(-|!)?([a-zA-Z]{1})(:[^;]+;)?/), regexp = new RegExp(directive[0]), modifier = directive[1] || "", plural = directive[3] || "", value = null;
directive = directive[2];
if (DIRECTIVE_KEY_MAP.hasOwnProperty(directive)) {
value = DIRECTIVE_KEY_MAP[directive];
value = Number(offsetObject[value]);
}
if (value !== null) {
if (modifier === "!") {
value = pluralize(plural, value);
}
if (modifier === "") {
if (value < 10) {
value = "0" + value.toString();
}
}
format = format.replace(regexp, value.toString());
}
}
}
format = format.replace(/%%/, "%");
return format;
};
}
function pluralize(format, count) {
var plural = "s", singular = "";
if (format) {
format = format.replace(/(:|;|\s)/gi, "").split(/\,/);
if (format.length === 1) {
plural = format[0];
} else {
singular = format[0];
plural = format[1];
}
}
if (Math.abs(count) === 1) {
return singular;
} else {
return plural;
}
}
// importante
var Countdown = function(el, finalDate, callback) {
this.el = el;
this.$el = $(el);
this.interval = null;
this.offset = {};
this.instanceNumber = instances.length;
instances.push(this);
this.$el.data("countdown-instance", this.instanceNumber);
if (callback) {
this.$el.on("update.countdown", callback);
this.$el.on("stoped.countdown", callback);
this.$el.on("finish.countdown", callback);
}
this.setFinalDate(finalDate);
this.start();
};
$.extend(Countdown.prototype, {
start: function() {
if (this.interval !== null) {
clearInterval(this.interval);
}
var self = this;
this.update();
this.interval = setInterval(function() {
self.update.call(self);
}, PRECISION);
},
stop: function() {
clearInterval(this.interval);
this.interval = null;
this.dispatchEvent("stoped");
},
pause: function() {
this.stop.call(this);
},
resume: function() {
this.start.call(this);
},
remove: function() {
this.stop();
instances[this.instanceNumber] = null;
delete this.$el.data().countdownInstance;
},
setFinalDate: function(value) { // pega o valor de data-countdown
//alert(value);
this.finalDate = parseDateString(value);
},
update: function() {
if (this.$el.closest("html").length === 0) {
this.remove();
return;
}
//this.totalSecsLeft = this.finalDate.getTime() - new Date().getTime();
/* setar hora do servidor */
/*
function horaServidor(){
//var qq = new Date("<?php echo date('D M d Y H:i:s').' GMT-0300 (Horário Padrão de Brasília)'; ?>").getTime();
//alert(''+qq);
//return new Date("<?php echo date('D M d Y H:i:s').' GMT-0300 (Horário Padrão de Brasília)'; ?>").getTime();
return new Date("<?php echo date('D M d Y H:i:s').' GMT-0300 (Horário Padrão de Brasília)'; ?>");
//setInterval(horaServidor(), 1000);
}
*/
this.totalSecsLeft = this.finalDate.getTime() - horaServer();
//this.totalSecsLeft = this.finalDate.getTime() - horaServidor().getTime();
//this.totalSecsLeft = this.finalDate.getTime() - new Date('Sat Oct 26 2019 18:37:04 GMT-0300 (Horário Padrão de Brasília)').getTime();
// this.totalSecsLeft = this.finalDate.getTime() - new Date().getTime(); LINHA ORIGINAL
this.totalSecsLeft = Math.ceil(this.totalSecsLeft / 1e3);
this.totalSecsLeft = this.totalSecsLeft < 0 ? 0 : this.totalSecsLeft;
this.offset = {
seconds: this.totalSecsLeft % 60,
minutes: Math.floor(this.totalSecsLeft / 60) % 60,
hours: Math.floor(this.totalSecsLeft / 60 / 60) % 24,
days: Math.floor(this.totalSecsLeft / 60 / 60 / 24) % 7,
totalDays: Math.floor(this.totalSecsLeft / 60 / 60 / 24),
weeks: Math.floor(this.totalSecsLeft / 60 / 60 / 24 / 7),
months: Math.floor(this.totalSecsLeft / 60 / 60 / 24 / 30),
years: Math.floor(this.totalSecsLeft / 60 / 60 / 24 / 365)
};
if (this.totalSecsLeft === 0) {
this.stop();
this.dispatchEvent("finish");
} else {
this.dispatchEvent("update");
}
},
dispatchEvent: function(eventName) {
var event = $.Event(eventName + ".countdown");
event.finalDate = this.finalDate;
event.offset = $.extend({}, this.offset);
event.strftime = strftime(this.offset);
this.$el.trigger(event);
}
});
$.fn.countdown = function() {
var argumentsArray = Array.prototype.slice.call(arguments, 0);
return this.each(function() {
var instanceNumber = $(this).data("countdown-instance");
if (instanceNumber !== undefined) {
var instance = instances[instanceNumber], method = argumentsArray[0];
if (Countdown.prototype.hasOwnProperty(method)) {
instance[method].apply(instance, argumentsArray.slice(1));
} else if (String(method).match(/^[$A-Z_][0-9A-Z_$]*$/i) === null) {
instance.setFinalDate.call(instance, method);
instance.start();
} else {
$.error("Method %s does not exist on jQuery.countdown".replace(/\%s/gi, method));
}
} else {
new Countdown(this, argumentsArray[0], argumentsArray[1]);
}
});
};
});
</script>
</head>
<body>
<b>Countdown</b>
<div data-countdown="2019/10/26 20:30:31"></div>
<div data-countdown="2019/10/27 14:35:18"></div>
<div data-countdown="2019/10/26 12:30:35"></div>
<div data-countdown="2019/10/29 10:57:04"></div>
<script>
$('[data-countdown]').each(function() {
var $this = $(this), finalDate = $(this).data('countdown');
$this.countdown(finalDate, function(event) {
$this.html(event.strftime('%D dias %H:%M:%S'));
});
});
</script>
Idk whats wrong with your code but I can help you with another one that I used (u can adapt it):
<style>
#import url('https://fonts.googleapis.com/css?family=Lato:400,700|Montserrat:900');
.timer {
color: #F6F4F3;
text-align: center;
text-transform: uppercase;
font-family: 'Lato', sans-serif;
}
.days,
.hours,
.minutes,
.seconds {
display: inline-block;
padding: 5px;
min-width: 20%;
margin: 1px;
height: 70px;
border-radius: 5px;
text-align: center;
font-size: 12px;
}
.days {
background-color: #EF2F3C;
}
.hours {
background: #F6F4F3;
color: #183059;
}
.minutes {
background: #276FBF;
}
.seconds {
background: #F0A202;
}
.numbers {
font-family: 'Montserrat', sans-serif;
color: #183059;
font-size: 18px;
}
</style>
<?php
foreach ($events as $index => $event) { ?>
<div id="timer<?php echo $index; ?>" class="card-deck timer-wrap" data-event-date="<?php echo $formatted; ?>"></div>
<?php } ?>
<script>
initTimers('.timer-wrap');
function initTimers(selector) {
var timers = document.querySelectorAll(selector);
if (timers.length > 0) {
for (var i = 0; i < timers.length; i++) {
countdown(timers[i]);
}
}
}
function countdown(timerElem) {
const year = new Date().getFullYear();
const dat = new Date(timerElem.dataset.eventDate);
let timer = setInterval(function() {
const today = new Date().getTime();
const diff = dat - today;
let days = Math.floor(diff / (1000 * 60 * 60 * 24));
let hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
let seconds = Math.floor((diff % (1000 * 60)) / 1000);
timerElem.innerHTML =
"<div class=\"card days\"> \<div class=\"numbers\">" + days + "</div>days</div> \<div class=\"card hours\"> \
<div class=\"numbers\">" + hours + "</div>hours</div> \<div class=\"card minutes\"> \
<div class=\"numbers\">" + minutes + "</div>minutes</div> \<div class=\"card seconds\"> \
<div class=\"numbers\">" + seconds + "</div>seconds</div> \</div>";
}, 1000);
}
</script>
because I'm pretty new to JS, I can't understand how to implement multiple data series into my code
Here is my php page that I use as data grabber:
getTrendData-TIMEREQUESTED-hms.php
<?php
//Define possible Argument request
$format = $_GET['format'];
if($format=='json') {
header("Content-type: text/json");
}
//Define database credential
$servername = "localhost";
$username = "test";
$password = "test";
$dbname = "test";
try {
//Open connection to mysql_db from defined Database credentials
$connection = mysqli_connect($servername, $username, $password, $dbname) or die ("Error " . mysqli_error($connection));
$sql = "select TIMEREQUESTED,TS FROM TIMEREQUESTED ORDER BY TS;";
$result = mysqli_query($connection, $sql) or die ("Error in Selecting " . mysqli_error($connection));
//create an array
$data = array();
while($row = mysqli_fetch_assoc($result)) {
$TIMEREQUESTED = strtotime($row['TIMEREQUESTED'])*1000;
$TS = strtotime($row['TS'])*1000;
$data[] = array($TS, $TIMEREQUESTED);
}
echo json_encode($data);
//close the db connection
mysqli_close($connection);
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
Than I include in HighCharts with an Ajax call, that call himselfs each 2500 miliseconds,
getTrendData-TIMEREQUESTED-hms.php
[[1461241983000,5.67,0],[1461242015000,16.67,0],[1461242164000,16.67,0],[1461242303000,26.25,0],[1461242835000,-2.5,0],[1461242869000,-2.5,0],[1461242991000,1.5,0],[1461243034000,3.14,0],[1461243374000,-14.22,0],[1461243456000,-11.92,0],[1461244995000,0,0],[1461245036000,-3.6,140],[1461245208000,-3,140],[1461245260000,3.56,140],[1461245312000,2.1,140],[1461245346000,2.1,140],[1461245411000,3.5,140],[1461245442000,3.5,140],[1461245479000,-1,140],[1461245757000,-0.8,140],[1461245809000,-0.69,140]]
TIMEREQUESTED-hms.html
function buildTIMEREQUESTED() {
var chart;
var dataSource = 'getTrendData-TIMEREQUESTED-hms.php?format=json';
var ChartHeight = window.innerHeight;
function requestData() {
$.ajax({
url: dataSource,
success: function(points) {
chart.series[0].setData(points, true);
setTimeout(requestData, 2500);
},
cache: false
});
}
$(document).ready(function() {
//add our div for the chart
$("#container").append("<div id=chart-laptime style='width:100%''></div>");
chart = new Highcharts.Chart({
chart: {
height: ChartHeight,
renderTo: 'chart-laptime',
defaultSeriesType: 'line',
events: {
load: function() {
requestData();
}
},
},
tooltip: {
enabled: true,
formatter: function() {
s = (this.y / 1000);
m = Math.floor(s / 60);
h = Math.floor(m / 60);
s = s % 60;
m = m % 60;
h = h % 24;
if (h < 9) h = "0" + h;
if (m < 9) m = "0" + m;
if (s < 9) s = "0" + s;
return '<span style="color:black">Time Zero - </span>' + [m, s].join(':');
}
},
title: {
text: 'TIMEREQUESTED'
},
subtitle: {
text: 'BEST 5 CAR AVEREGE LAPTIME IN LAST 10 MINUTES'
},
xAxis: {
type: 'datetime',
title: {
text: 'RACE TIME'
}
},
yAxis: {
type: 'datetime',
dateTimeLabelFormats: {
millisecond: '%H:%M:%S',
},
//dateFormat: {"%H:%M:%S.%L"}
title: {
text: 'TIMEREQUESTED'
}
},
series: [{
name: 'TIMEREQUESTED',
showInLegend: false,
//tooltip: {type: 'datetime',},
data: [],
}]
}); //end chart
}); //end document.ready
}
In that way I can get the single series proper displayed, but with the MySQL query I'm able to get more columns from the database, and parsing in each rows of the json file,(As is showed in the JSON file from php request, there is a third values for each array) but I'm not able to understand how to display multiple data series, with on the xAxis always the first column of the JSON file, and on the yAxis each time a different columns.
Could you please give me some suggestions on how to display multi series on the same graph? It would be so much appreciated,
Best regards.
var dataForTwoSeries = [[1461241983000,5.67,0],[1461242015000,16.67,0],[1461242164000,16.67,0]]; //your data, just took 3 elements. Should work for any number of elements.
var seriesOne = [];
var seriesTwo = [];
$.each(dataForTwoSeries, function(index, dataPoints){
var seriesOneDataPoint = [dataPoints[0], dataPoints[1]];
var seriesTwoDataPoint = [dataPoints[0], dataPoints[2]];
seriesOne.push(seriesOneDataPoint);
seriesTwo.push(seriesTwoDataPoint);
});
And then you'll have to create 2 series in your chart object like
series: [{
name: 'seriesName1',
showInLegend: false,
data: [],
},{
name: 'seriesName2',
showInLegend: false,
data: [],
}]
And in your requestData method, set the data for both like
chart.series[0].setData(seriesOne, false); //redraw after setting data for second series
chart.series[1].setData(seriesTwo); //boolean redraw is true by default, don't need to pass it
EDIT : After your updated code, these are the changes you further need to make.
$.ajax({url: dataSource, success: function(dataForTwoSeries) //dataForTwoSeries is the data you get from the request
{
//var dataForTwoSeries = []; you don't need this.
var seriesOne = []; //these two don't have to be global.
var seriesTwo = [];
$.each(dataForTwoSeries, function(index, dataPoints){
var seriesOneDataPoint = [dataPoints[1], dataPoints[0]];
var seriesTwoDataPoint = [dataPoints[2], dataPoints[0]];
seriesOne.push(seriesOneDataPoint);
seriesTwo.push(seriesTwoDataPoint);
}); // draw chart after iteration and not during each interation
chart.series[0].setData(seriesOne, false); //redraw after setting data for second series
chart.series[1].setData(seriesTwo); //boolean redraw is true by default, don't need to pass it
setTimeout(requestData, 2500);
},
cache: false
});
I've update the code and now is free from syntax error, but I have no data displayed. I'm going to put some windows.allert() tu understand where the data flow is broken.
Here's the updated code:
<!DOCTYPE html>
<html>
<head>
<title>Strategy - Time Zero</title>
<script src="js/jquery/jquery-1.12.3.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="js/Highcharts/Highcharts-4.2.3/highcharts.js"></script>
<script src="js/Highcharts/Highcharts-4.2.3/modules/exporting.js"></script>
<script>
var chart;
var dataSource = 'getTrendData-TimeZero.php?format=json';
var ChartHeight = window.innerHeight;
var dataForTwoSeries = [];
var seriesOne = [];
var seriesTwo = [];
function requestData() {
$.ajax({url: dataSource, success: function(dataPoints)
{
$.each(dataForTwoSeries, function(index, dataPoints){
var seriesOneDataPoint = [dataPoints[1], dataPoints[0]];
var seriesTwoDataPoint = [dataPoints[2], dataPoints[0]];
window.alert(seriesOneDataPoint)
seriesOne.push(seriesOneDataPoint);
seriesTwo.push(seriesTwoDataPoint);
chart.series[0].setData(seriesOne, false); //redraw after setting data for second series
chart.series[1].setData(seriesTwo); //boolean redraw is true by default, don't need to pass it
setTimeout(requestData, 2500);
});
},
cache: false
});
}
$(document).ready(function() {
//add our div for the chart
$("#container").append("<div id=chart-TimeZero style='width:100%''></div>");
//StockChart
//Chart
chart = new Highcharts.Chart({
chart: {
height: ChartHeight,
renderTo: 'chart-TimeZero',
defaultSeriesType: 'line',
events: {
load: function() {
requestData();
}
},
},
tooltip: {
enabled: true,
formatter: function() {
if (this.y < 0)
{
h = Math.ceil(this.y / 3600);
m = Math.ceil(this.y / 60);
s = Math.ceil(this.y % 60);
h = Math.abs(h);
m = Math.abs(m);
s = Math.abs(s);
s = s % 60;
m = m % 60;
h = h % 24;
if (h < 9) h = "-0" + h;
if (m < 9) m = "0" + m;
if (s < 9) s = "0" + s;
}
else
{
h = Math.floor(this.y / 3600);
m = Math.floor(this.y / 60);
s = Math.floor(this.y % 60);
h = Math.abs(h);
m = Math.abs(m);
s = Math.abs(s);
s = s % 60;
m = m % 60;
h = h % 24;
if (h < 9) h = "0" + h;
if (m < 9) m = "0" + m;
if (s < 9) s = "0" + s;
}
return '<span style="color:black">Time Zero</span> ' + [h, m, s].join(':');
}
},
title: {
text: 'TIME ZERO'
},
subtitle: {
text: 'BEST 5 CAR AVEREGE LAPTIME IN LAST 10 MINUTES'
},
xAxis: {
type: 'datetime',
title: {text: 'DAY TIME'}
},
yAxis: {
title: {text: 'TIME ZERO'},
labels: {
formatter: function() {
if (this.value < 0)
{
h = Math.ceil(this.value / 3600);
m = Math.ceil(this.value / 60);
s = Math.ceil(this.value % 60);
h = Math.abs(h);
m = Math.abs(m);
s = Math.abs(s);
s = s % 60;
m = m % 60;
h = h % 24;
if (h < 9) h = "-0" + h;
if (m < 9) m = "0" + m;
if (s < 9) s = "0" + s;
}
else
{
h = Math.floor(this.value / 3600);
m = Math.floor(this.value / 60);
s = Math.floor(this.value % 60);
h = Math.abs(h);
m = Math.abs(m);
s = Math.abs(s);
s = s % 60;
m = m % 60;
h = h % 24;
if (h < 9) h = "0" + h;
if (m < 9) m = "0" + m;
if (s < 9) s = "0" + s;
}
return [h, m, s].join(':');
}
}
},
series: [{
name: 'seriesName1',
showInLegend: true,
data: [],
},{
name: 'seriesName2',
showInLegend: true,
data: [],
}]
}); //end chart
}); //end document.ready
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>
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)); } });
;)
I am trying to redirect to my homepage from a splash (age verification) page, and it just keeps popping up the same age verification page.
I have the ageVerify.php script in the root folder and I have the other script at the top of my template file page. I just need to find the correct file structure format to redirect too after someone hits "yes i'm 18"
The code below doesn't work when added to the top of my column1.phtml file - it just keeps going back and recalling the verify.php script. Any ideas would be very helpful!
<?php
function verified()
{
$redirect_url='http://www.johnsoncreeksmokejuice.com.vhost.zerolag.com/verify.php';
$expires=-1;
session_start();
$validated=false;
if (!empty($_COOKIE["verified"])) {
$validated=true;
}
if (!$validated && isset($_SESSION['verified'])) {
$validated=true;
}
if (is_numeric($expires) && $expires==-1 && !isset($_SESSION['verified'])) {
$validated=false;
}
if ($validated) {
return;
}
else {
$redirect_url=$redirect_url."?return=index.php&x=".$expires;
Header('Location: '.$redirect_url);
exit(0);
}
}
verified();
?>
If $_SESSION is not set always will evaluate this
if (is_numeric($expires) && $expires==-1 && !isset($_SESSION['verified'])) {
$validated=false;
}
Just fix it and should work.
Assuming that everything else is fine, I would replace
if (!empty($_COOKIE["verified"])) {
$validated=true;
}
if (!$validated && isset($_SESSION['verified'])) {
$validated=true;
}
if (is_numeric($expires) && $expires==-1 && !isset($_SESSION['verified'])) {
$validated=false;
}
By:
if ( (isset($_COOKIE["verified"] && !empty($_COOKIE["verified"])) OR isset($_SESSION['verified']) ) {
$validated=true;
}
So, if user has a non-empty "verified" cookie or a "verified" session set, it assumes he is validated.
Chose to use a javascript alternative. Worked out much easier for me:
function writeCookie(key,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = key+"="+value+expires+"; path=/";
}
function readCookie(key) {
var nameEQ = key + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function ageGate() {
var monthDays = {
1: 31,
2: 29,
3: 31,
4: 30,
5: 31,
6: 30,
7: 31,
8: 31,
9: 30,
10: 31,
11: 30,
12: 31
};
var months = {
1: 'January',
2: 'February',
3: 'March',
4: 'April',
5: 'May',
6: 'June',
7: 'July',
8: 'August',
9: 'September',
10: 'October',
11: 'November',
12: 'December'
};
var monthOptions = [];
var dayOptions = {};
var yearOptions = [];
for (var month in monthDays) {
var days = monthDays[month];
monthOptions.push('<option value="' + month + '">' + months[month] + '</option>');
dayOptions[month] = [];
for (var i=1; i <= days; i++) {
var day = i;
dayOptions[month].push('<option value="' + day + '">' + day + '</option>');
}
}
var currentYear = new Date();
currentYear = currentYear.getFullYear();
var startYear = currentYear - 120;
for (var y=currentYear; y > startYear; y--) {
yearOptions.push('<option value="' + y + '">' + y + '</option>');
}
$s(document).ready(function(){
var monthHtml = '';
for (var j=0; j < monthOptions.length; j++) {
var html = monthOptions[j];
monthHtml += html;
}
$s('#ageMonth').html(monthHtml);
var yearHtml = '';
for (var i=0; i < yearOptions.length; i++) {
yearHtml += yearOptions[i];
}
$s('#ageYear').html(yearHtml);
$s('#ageMonth').bind('change', function(){
var dayHtml = '';
var month = $s(this).val();
for (var i=0; i < dayOptions[month].length; i++) {
dayHtml += dayOptions[month][i];
}
$s('#ageDay').html(dayHtml);
});
$s('#ageEnterSite').click(function(e){
e.preventDefault();
var date = new Date();
date.setMonth($s('#ageMonth').val() - 1);
date.setDate($s('#ageDay').val());
date.setYear($s('#ageYear').val());
var maxDate = new Date();
// alert(maxDate.getFullYear());
maxDate.setYear(maxDate.getFullYear() - 18);
if (date <= maxDate) {
writeCookie('jcsj_age_verified', '1', 30);
$s('#age-gate').fadeOut(function(){
$s(this).remove();
$s('body').removeClass('age-gate-visible');
});
}
else {
window.location.href = 'http://google.com';
}
});
$s('#ageMonth').change(); // load default month
// $s('#ageDay').prop('disabled', true);
setTimeout(function(){
$s('body').addClass('age-gate-visible');
$s('#age-gate').fadeIn();
}, 200);
});
}
if (readCookie('jcsj_age_verified')) {
} else {
ageGate();
}
</script>
<script type="text/javascript">
var t;
function startTimer(){
t=setTimeout("document.location='../login/logout.php'", 50000);
}
function stopTimer(){
clearTimeout(t);
}
</script>
This is my script for auto logout,
i want to show the countdown timer, How to create and show the timer,
Also i want to make alive when the user hit the body of the page,
Also timer should reset and then restart again when system is idle,
How to make it,
(Timer should show , that is ,
timer should run when people not touching the system ,
if user touch the system then counter should restart )
Use this function:
function timer(elem, starttime, endtime, speed, funktion, count) {
if (!endtime) endtime = 0;
if (!starttime) starttime = 10;
if (!speed) speed = 1;
speed = speed * 1000;
if ($(elem).html() || $(elem).val()) {
if (count == "next" && starttime > endtime) starttime--;
else if (count == "next" && starttime < endtime) starttime++;
if ($(elem).html()) $(elem).html(starttime);
else if ($(elem).val()) $(elem).val(starttime);
if (starttime != endtime && $(elem).html()) setTimeout(function() {
timer(elem, $(elem).html(), endtime, speed / 1000, funktion, 'next');
}, speed);
if (starttime != endtime && $(elem).val()) setTimeout(function() {
timer(elem, $(elem).val(), endtime, speed / 1000, funktion, 'next');
}, speed);
if (starttime == endtime && funktion) funktion();
} else return;
}
Example
timer("#timer", 50, 0, 1, function() {
location.href = "../login/logout.php";
});
my example:
Updated to check if the user is Idle (is set to 2 seconds, this makes testing easier, i'd recommend at least 5 or 10 minutes).
<body onload="setTimeout('startCountDown()',2000);" onmousemove="resetTimer();">
<form name="counter"><input type="text" size="5" name="timer" disabled="disabled" /></form>
<script type="text/javascript">
<!--
// edit startSeconds as you see fit
// simple timer example provided by Thomas
var startSeconds = 10;
var milisec = 0;
var seconds=startSeconds;
var countdownrunning = false
var idle = false;
document.counter.timer.value=startSeconds;
function CountDown()
{
if(idle == true)
{
if (milisec<=0)
{
milisec=9
seconds-=1
}
if (seconds<=-1)
{
document.location='../login/logout.php';
milisec=0
seconds+=1
return;
}
else
milisec-=1;
document.counter.timer.value=seconds+"."+milisec;
setTimeout("CountDown()",100);
}
else
{
return;
}
}
function startCountDown()
{
document.counter.timer.value=startSeconds;
seconds = startSeconds;
milisec = 0
document.counter.timer.style.display = 'block';
idle = true;
CountDown();
document.getElementById("alert").innerHTML = 'You are idle. you will be logged out after ' + startSeconds + ' seconds.';
countdownrunning = false;
}
function resetTimer()
{
document.counter.timer.style.display = 'none';
idle = false;
document.getElementById("alert").innerHTML = '';
if(!countdownrunning)
setTimeout('startCountDown()',2000);
countdownrunning = true;
}
-->
</script>
my code here...after modified a bit...it works for me...
var startSeconds = 10;
var milisec = 0;
var seconds=startSeconds;
var countdownrunning = false
var idle = false;
document.counter.timer.value=startSeconds;
function CountDown()
{
if(idle == true)
{
if (milisec<=0)
{
milisec=9
seconds-=1
}
if (seconds<=-1)
{
document.location='../login/logout.php';
milisec=0
seconds+=1
return;
}
else
seconds-=1;
setTimeout("CountDown()",1000);
}
else
{
return;
}
}
function startCountDown()
{
seconds = startSeconds;
milisec = 0
idle = true;
CountDown();
document.getElementById("alert").innerHTML = 'You are idle. you will be logged out after ' + startSeconds + ' seconds.';
countdownrunning = false;
}
function resetTimer()
{
idle = false;
if(countdownrunning)
setTimeout('startCountDown()',2000);
countdownrunning = true;
}