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>
Related
Here is my code that i am using for fetching data from Google Maps also fetching coordinates of polygon and polylines from Drawer.
**
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta charset="UTF-8" />
<title>Muhammad</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=drawing"></script>
<style type="text/css">
#map,
html,
body {
padding: 0;
margin: 0;
width: 95%;
height: 700px;
float: right;
}
#panel {
width: 200px;
font-family: Arial, sans-serif;
font-size: 13px;
float: right;
margin: 10px;
}
#color-palette {
clear: both;
}
.color-button {
width: 14px;
height: 14px;
font-size: 0;
margin: 2px;
float: left;
cursor: pointer;
}
#delete-button {
margin-top: 5px;
}
</style>
<script type="text/javascript">
var drawingManager;
var selectedShape;
var colors = ["#1E90FF", "#FF1493", "#32CD32", "#FF8C00", "#4B0082"];
var selectedColor;
var colorButtons = {};
function clearSelection() {
if (selectedShape) {
selectedShape.setEditable(false);
selectedShape = null;
}
}
function setSelection(shape) {
clearSelection();
// getting shape coordinates
var v = shape.getPath();
var coords = [];
for (var i = 0; i < v.getLength(); i++) {
var xy = v.getAt(i);
console.log(`Cordinate lat ${i}: ` + xy.lat() + `and long ${i}: ` + xy.lng());
var x = document.createElement('INPUT');
x.setAttribute('type', 'text');
x.setAttribute('value', xy);
document.body.appendChild(x);
coords.push([xy.lat()], [xy.lng()]);
}
console.log(coords + 'Muhammad');
document.getElementById('coords_value').value = coords;
selectedShape = shape;
shape.setEditable(true);
selectColor(shape.get("fillColor") || shape.get("strokeColor"));
}
function saveButton(shape) {
}
function deleteSelectedShape() {
if (selectedShape) {
selectedShape.setMap(null);
}
}
function selectColor(color) {
selectedColor = color;
for (var i = 0; i < colors.length; ++i) {
var currColor = colors[i];
colorButtons[currColor].style.border = currColor == color ? "2px solid #789" : "2px solid #fff";
}
// Retrieves the current options from the drawing manager and replaces the
// stroke or fill color as appropriate.
var polylineOptions = drawingManager.get("polylineOptions");
polylineOptions.strokeColor = color;
drawingManager.set("polylineOptions", polylineOptions);
var rectangleOptions = drawingManager.get("rectangleOptions");
rectangleOptions.fillColor = color;
drawingManager.set("rectangleOptions", rectangleOptions);
var circleOptions = drawingManager.get("circleOptions");
circleOptions.fillColor = color;
drawingManager.set("circleOptions", circleOptions);
var polygonOptions = drawingManager.get("polygonOptions");
polygonOptions.fillColor = color;
drawingManager.set("polygonOptions", polygonOptions);
}
function setSelectedShapeColor(color) {
console.log("fn setSelectedShapeColor()");
console.log(selectedShape);
if (selectedShape) {
if (selectedShape.type == google.maps.drawing.OverlayType.POLYLINE) {
selectedShape.set("strokeColor", color);
} else {
selectedShape.set("fillColor", color);
}
}
}
function makeColorButton(color) {
var button = document.createElement("span");
button.className = "color-button";
button.style.backgroundColor = color;
google.maps.event.addDomListener(button, "click", function() {
selectColor(color);
setSelectedShapeColor(color);
});
return button;
}
function buildColorPalette() {
var colorPalette = document.getElementById("color-palette");
for (var i = 0; i < colors.length; ++i) {
var currColor = colors[i];
var colorButton = makeColorButton(currColor);
colorPalette.appendChild(colorButton);
colorButtons[currColor] = colorButton;
}
selectColor(colors[0]);
}
function initialize() {
var pakistan = new google.maps.LatLng(30.3753, 69.3451);
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 3,
center: pakistan,
disableDefaultUI: true,
zoomControl: true
});
var marker = new google.maps.Marker({
position: pakistan,
map: map
});
var polyOptions = {
strokeWeight: 0,
fillOpacity: 0.45,
editable: true,
draggable: true
};
// Creates a drawing manager attached to the map that allows the user to draw
// markers, lines, and shapes.
drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
markerOptions: {
draggable: true
},
polylineOptions: {
editable: true,
draggable: true
},
rectangleOptions: polyOptions,
circleOptions: polyOptions,
polygonOptions: polyOptions,
map: map
});
google.maps.event.addListener(drawingManager, "overlaycomplete", function(e) {
if (e.type !== google.maps.drawing.OverlayType.MARKER) {
// Switch back to non-drawing mode after drawing a shape.
drawingManager.setDrawingMode(null);
// Add an event listener that selects the newly-drawn shape when the user
// mouses down on it.
var newShape = e.overlay;
newShape.type = e.type;
google.maps.event.addListener(newShape, "click", function(e) {
if (e.vertex !== undefined) {
if (newShape.type === google.maps.drawing.OverlayType.POLYGON) {
var path = newShape.getPaths().getAt(e.path);
path.removeAt(e.vertex);
if (path.length < 3) {
newShape.setMap(null);
}
}
if (newShape.type === google.maps.drawing.OverlayType.POLYLINE) {
var path = newShape.getPath();
path.removeAt(e.vertex);
if (path.length < 2) {
newShape.setMap(null);
}
}
}
setSelection(newShape);
saveButton(newShape);
});
setSelection(newShape);
saveButton(newShape);
}
});
// Clear the current selection when the drawing mode is changed, or when the
// map is clicked.
google.maps.event.addListener(drawingManager, "drawingmode_changed", clearSelection);
google.maps.event.addListener(map, "click", clearSelection);
google.maps.event.addDomListener(document.getElementById("delete-button"), "click", deleteSelectedShape);
buildColorPalette();
}
google.maps.event.addDomListener(window, "load", initialize);
var IO = {
//returns array with storable google.maps.Overlay-definitions
IN: function(
arr, //array with google.maps.Overlays
encoded //boolean indicating if pathes should be stored encoded
) {
var shapes = [],
goo = google.maps,
shape,
tmp;
for (var i = 0; i < arr.length; i++) {
shape = arr[i];
tmp = {
type: this.t_(shape.type),
id: shape.id || null
};
switch (tmp.type) {
case "CIRCLE":
tmp.radius = shape.getRadius();
tmp.geometry = this.p_(shape.getCenter());
break;
case "MARKER":
tmp.geometry = this.p_(shape.getPosition());
break;
case "RECTANGLE":
tmp.geometry = this.b_(shape.getBounds());
break;
case "POLYLINE":
tmp.geometry = this.l_(shape.getPath(), encoded);
break;
case "POLYGON":
tmp.geometry = this.m_(shape.getPaths(), encoded);
break;
}
shapes.push(tmp);
}
return shapes;
},
//returns array with google.maps.Overlays
OUT: function(
arr, //array containg the stored shape-definitions
map //map where to draw the shapes
) {
var shapes = [],
goo = google.maps,
map = map || null,
shape,
tmp;
for (var i = 0; i < arr.length; i++) {
shape = arr[i];
switch (shape.type) {
case "CIRCLE":
tmp = new goo.Circle({
radius: Number(shape.radius),
center: this.pp_.apply(this, shape.geometry)
});
break;
case "MARKER":
tmp = new goo.Marker({
position: this.pp_.apply(this, shape.geometry)
});
break;
case "RECTANGLE":
tmp = new goo.Rectangle({
bounds: this.bb_.apply(this, shape.geometry)
});
break;
case "POLYLINE":
tmp = new goo.Polyline({
path: this.ll_(shape.geometry)
});
break;
case "POLYGON":
tmp = new goo.Polygon({
paths: this.mm_(shape.geometry)
});
break;
}
tmp.setValues({
map: map,
id: shape.id
});
shapes.push(tmp);
}
return shapes;
},
l_: function(path, e) {
path = path.getArray ? path.getArray() : path;
if (e) {
return google.maps.geometry.encoding.encodePath(path);
} else {
var r = [];
for (var i = 0; i < path.length; ++i) {
r.push(this.p_(path[i]));
}
return r;
}
},
ll_: function(path) {
if (typeof path === "string") {
return google.maps.geometry.encoding.decodePath(path);
} else {
var r = [];
for (var i = 0; i < path.length; ++i) {
r.push(this.pp_.apply(this, path[i]));
}
return r;
}
},
m_: function(paths, e) {
var r = [];
paths = paths.getArray ? paths.getArray() : paths;
for (var i = 0; i < paths.length; ++i) {
r.push(this.l_(paths[i], e));
}
return r;
},
mm_: function(paths) {
var r = [];
for (var i = 0; i < paths.length; ++i) {
r.push(this.ll_.call(this, paths[i]));
}
return r;
},
p_: function(latLng) {
return [latLng.lat(), latLng.lng()];
},
pp_: function(lat, lng) {
return new google.maps.LatLng(lat, lng);
},
b_: function(bounds) {
return [this.p_(bounds.getSouthWest()), this.p_(bounds.getNorthEast())];
},
bb_: function(sw, ne) {
return new google.maps.LatLngBounds(this.pp_.apply(this, sw), this.pp_.apply(this, ne));
},
t_: function(s) {
var t = ["CIRCLE", "MARKER", "RECTANGLE", "POLYLINE", "POLYGON"];
for (var i = 0; i < t.length; ++i) {
if (s === google.maps.drawing.OverlayType[t[i]]) {
return t[i];
}
}
}
};
</script>
</head>
<body>
<div id="panel">
<div id="color-palette"></div>
<form method="POST" action="submit.php">
<input type="text" id="coords_value" name="coords" value="Muhammad">
<button onclick="saveButton()">Muhammad</button>
</form>
<div><button id="delete-button">Delete Selected Shape</button></div>
</div>
<div id="map"></div>
</body>
</html>
**
and my submit.php file
**
<?php $servername = "localhost";
$username = "root";
$password = "";
$db = "users";
$mysqli = new mysqli($servername, $username, $password, $db);
// SET #g = 'POLYGON($_POST[coords])';
$coords = $_POST['coords'];
//$stmt = "INSERT INTO polygon_data (polygon_values) VALUES (GeomFromText('POLYGON((30 10, 40 40, 20 40, 10 20, 30 10))'))";
$stmt = "INSERT INTO polygon_data (polygon_values) VALUES (PolygonFromText('POLYGON((40.95269385429521, -74.14416921914062,40.959175907354734, -74.11670339882812,40.9419322410085, -74.13009298623047))'))";
if ($mysqli->query($stmt) === TRUE) {
echo "feedback sucessfully submitted";
} else {
echo "Error: " . $stmt . "<br>" . $mysqli->error;
}
$mysqli->close();
?>
**
For example if i draw a pollygon and then i gets the following points that are not correct, this is because in a polygon the first and last point's coordinates would be same but in mine case it seems to be somehow different as below.
(61.81599137659937,102.17362172851564,62.956500953314375,117.64237172851564,56.80241721826492,111.84159047851564)
and this difference is a huge difference.And i did not getting my expecting result?
Thanks
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
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>
I have a php/javascript code that takes a GPS coordinate from an Iphone/website app (instamapper) and adds it to my website page. (using snippets of other peoples code examples so far) I'd like to change the popup from displaying the decimal coordinates to proper Lat / Long but cant quite work it out. Any help or pointers you guys could give would be great. My code is below.
found here http://www.morvargh-sailing.co.uk/tracker/test2.php
<?php
$key = "16194603621692259587";
$fichier = "http://www.instamapper.com/api?action=getPositions&key=".$key."&num=1";
$fp=#fopen($fichier,"r");
$texte = "";
if($fp)
{
while(!feof($fp))
{
$texte .= fgets($fp,1024);
}
}
$donnees = explode(',',$texte);
/*
0 : first line plus device number
1 : Device label
2. Position timestamp in UTC (number of seconds since January 1, 1970)
3. Latitude
4. Longitude
5. Altitude in meters
6. Speed in meters / second
7. Heading in degrees
*/
date_default_timezone_set('GMT');
$name = $donnees[1];
$date = date('H:i:s d-m-Y e', $donnees[2]);
$lat = $donnees[3];
$longitude = $donnees[4];
$altitude = $donnees[5];
$speed = $donnees[6];
$heading = $donnees[7];
echo('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Where am I</title>
<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAA_GqVjhr7wgurGjr_zR-wJxSbxjqNwl0XTkuBKGwUYonF3JCDWBRyXrxgjwLgrUjcet0gLjyGZOGwCA" type="text/javascript"></script>
<style type="text/css">
v\:* {behavior:url(#default#VML);}
html, body {width: 100%; height: 350px}
body, form, p {margin: 0; padding: 0; text-align:center; font-family:"lucida grande","trebuchet ms",sans-serif; font-size:12px;}
a:link, a:visited, a:hover {color: #369; background:transparent; text-decoration: none;}
#instamapper {position:absolute; left:80px; bottom:10px;}
#instamapper p {text-align:right;}
</style>
</head>
<body onLoad="showAddress(\''.$lat.', '.$longitude.'\'); return false" onunload="GUnload()">
<div id="map" style="width: 100%; height: 100%;"></div>
<div id="instamapper">
<p>
GPS tracking powered by InstaMapper
<p>
<div>
<script type="text/javascript">
//<![CDATA[
var momento = "'.$date.'";
var altitud = "'.$altitude.'" + "m";
var velocidad = "'.$speed.'" + " Km/h";
var longitude = "'.$longitude.'";
var latitude = "'.$lat.'";
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
var geocoder = new GClientGeocoder();
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
function showAddress(address) {
geocoder.getLatLng(
address,
function(point) {
if (!point) {
alert("\"" + address + "\" no encontrado");
} else {
map.setCenter(point, 12);
var marker = new GMarker(point);
var info = "<b>Last known location:</b><p>Time: " + momento + "<br>Latitude: " + latitude + "<br>Longitude: " + longitude + "<br>Heading: " + '.$heading.' +"º";
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(info);
});
map.addOverlay(marker);
marker.openInfoWindowHtml(info);
}
}
);
}
}
//]]>
</script>
</body>
</html>');
?>
Try this function: http://jsfiddle.net/eAUJr/1/
function format(newLat, newLng) {
if (newLat < 0) {
newLat = myround(Math.abs(newLat)) + "S";
} else {
newLat = myround(newLat) + "N";
}
if (newLng < 0) {
newLng = myround(Math.abs(newLng)) + "W";
} else {
newLng = myround(newLng) + "E";
}
return[newLat, newLng];
}
function myround(val) {
deg = parseInt(val);
val -= deg;
val *= 60;
min = parseInt(val);
val -= min;
val *= 60;
sec = parseInt(val);
remainder = val - sec;
if(remainder >= 0.5) {
sec += 1;
}
return deg + "°" + min + "'" + sec + '"';
}
document.write(format(-0.000277778, 20.292))
// output: 0°0'1"S,20°17'31"E