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();
I hope someone will be able to help me out since I dont want to break something.
It's a big thanks in advance.
Javascript doesn't have a nice way of printing out the day name like PHP does, you have to code the names manually, starting with Sunday:
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var date = new Date();
console.log(days[date.getDay()]); // Wednesday
More info here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getDay
EDIT: If you want to do this all with the jclock plugin, you can use the format parameter to specify the output format. The format symbol for the day name is %A. For an example using the format option, see: https://github.com/dsparling/jclock/blob/master/examples/clock2.html
Related
Am using metronic template for web-application, jquery datepicker working in chrome but in firefox while edit date, the datepicker format show like NaN-NaN-NaN.
My codes are:
$('.edit').on('click', function () {
var date, id = this.id;
$.getJSON('{{path('getuser')}}?userid=' + id, function (data) {
$("#user_id").val(id);
$("#page_type").val('edit');
$("#empid").val(data['user'][0].EmployeeID);
$("#empid").attr("disabled", "disabled");
$("#fname").val(data['user'][0].FirstName);
$("#lname").val(data['user'][0].LastName);
if (data['user'][0].DOJ) {
var d = new Date(data['user'][0].DOJ);
var day = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
if (month < 10) {
month = "0" + month;
}
if (day < 10) {
day = "0" + day;
}
date = month + "-" + day + "-" + year;
$("#doj").val(date);
} else {
date = '';
$("#doj").val('');
}
var arr = data['roles'];
$.each(arr, function (i, val) {
$('#my_multi_select1').multiSelect('select', arr[i].RoleID);
});
var locname = $("select[name=location] option[value='" + data['user'][0].LocationID + "']").text();
$('#location option').filter(function () {
return $(this).text() === locname;
}).prop('selected', true);
$("#s2id_location > a > .select2-chosen").text(locname);
$("#uname").val(data['user'][0].UserName);
$("#email").val(data['user'][0].EmailID);
$("#password").val(data['user'][0].Password);
$('#portlet-config').modal('show');
});
});
output:
NaN-NaN-NaN
Need solution.
Thanks for advance.
I got a solution.
solution is, in database change datetime to date.
I am using the timeago plugin http://timeago.yarp.com/
It seems to work if the element is generated within the html however if I try to echo it to the page from php it does not work.
Please see my files below: 1.php where you can see the issue of the correct timeago in the "load_out" div and the incorrect value (from php) in the "div2" div; showall.php; there's a basic connect.php file which connects to a database "test" containing a table "comments" - I won't inlcude it here; finally the jquery plugin which I have called timeago2.js. Please see files below:
1.php:
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="timeago2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
jQuery("abbr.timeago").timeago();
$(".div2").load('showall.php');
});
</script>
</head>
<body>
<div class="load_out" style="border:1px solid red">
<abbr class="timeago" title="2014-07-30T20:00:17Z">July 17, 2008</abbr>
</div>
<div class="div2">
<div>
</body>
</html>
showall.php
<?php
function showPosts() {
#mysql_connect("localhost","root","")or die("could not connect to mysql");
#mysql_select_db("test")or die("no database");
$me = mysql_query("SELECT * FROM comment");
while($row=mysql_fetch_array($me)){
echo '<abbr class="timeago" title="2014-07-30T20:00:17Z">hi</abbr>';
}
}
return showPosts();
?>
timeago2.js:
/**
* Timeago is a jQuery plugin that makes it easy to support automatically
* updating fuzzy timestamps (e.g. "4 minutes ago" or "about 1 day ago").
*
* #name timeago
* #version 1.4.1
* #requires jQuery v1.2.3+
* #author Ryan McGeary
* #license MIT License - http://www.opensource.org/licenses/mit-license.php
*
* For usage and examples, visit:
* http://timeago.yarp.com/
*
* Copyright (c) 2008-2013, Ryan McGeary (ryan -[at]- mcgeary [*dot*] org)
*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
$.timeago = function(timestamp) {
if (timestamp instanceof Date) {
return inWords(timestamp);
} else if (typeof timestamp === "string") {
return inWords($.timeago.parse(timestamp));
} else if (typeof timestamp === "number") {
return inWords(new Date(timestamp));
} else {
return inWords($.timeago.datetime(timestamp));
}
};
var $t = $.timeago;
$.extend($.timeago, {
settings: {
refreshMillis: 60000,
allowPast: true,
allowFuture: false,
localeTitle: false,
cutoff: 0,
strings: {
prefixAgo: null,
prefixFromNow: null,
suffixAgo: "ago",
suffixFromNow: "from now",
inPast: 'any moment now',
seconds: "less than a minute",
minute: "about a minute",
minutes: "%d minutes",
hour: "about an hour",
hours: "about %d hours",
day: "a day",
days: "%d days",
month: "about a month",
months: "%d months",
year: "about a year",
years: "%d years",
wordSeparator: " ",
numbers: []
}
},
inWords: function(distanceMillis) {
if(!this.settings.allowPast && ! this.settings.allowFuture) {
throw 'timeago allowPast and allowFuture settings can not both be set to false.';
}
var $l = this.settings.strings;
var prefix = $l.prefixAgo;
var suffix = $l.suffixAgo;
if (this.settings.allowFuture) {
if (distanceMillis < 0) {
prefix = $l.prefixFromNow;
suffix = $l.suffixFromNow;
}
}
if(!this.settings.allowPast && distanceMillis >= 0) {
return this.settings.strings.inPast;
}
var seconds = Math.abs(distanceMillis) / 1000;
var minutes = seconds / 60;
var hours = minutes / 60;
var days = hours / 24;
var years = days / 365;
function substitute(stringOrFunction, number) {
var string = $.isFunction(stringOrFunction) ? stringOrFunction(number, distanceMillis)
: stringOrFunction;
var value = ($l.numbers && $l.numbers[number]) || number;
return string.replace(/%d/i, value);
}
var words = seconds < 45 && substitute($l.seconds, Math.round(seconds)) ||
seconds < 90 && substitute($l.minute, 1) ||
minutes < 45 && substitute($l.minutes, Math.round(minutes)) ||
minutes < 90 && substitute($l.hour, 1) ||
hours < 24 && substitute($l.hours, Math.round(hours)) ||
hours < 42 && substitute($l.day, 1) ||
days < 30 && substitute($l.days, Math.round(days)) ||
days < 45 && substitute($l.month, 1) ||
days < 365 && substitute($l.months, Math.round(days / 30)) ||
years < 1.5 && substitute($l.year, 1) ||
substitute($l.years, Math.round(years));
var separator = $l.wordSeparator || "";
if ($l.wordSeparator === undefined) { separator = " "; }
return $.trim([prefix, words, suffix].join(separator));
},
parse: function(iso8601) {
var s = $.trim(iso8601);
s = s.replace(/\.\d+/,""); // remove milliseconds
s = s.replace(/-/,"/").replace(/-/,"/");
s = s.replace(/T/," ").replace(/Z/," UTC");
s = s.replace(/([\+\-]\d\d)\(\d\d)/," $1$2"); // -04:00 -> -0400
s = s.replace(/([\+\-]\d\d)$/," $100"); // +09 -> +0900
return new Date(s);
},
datetime: function(elem) {
var iso8601 = $t.isTime(elem) ? $(elem).attr("datetime") : $(elem).attr("title");
return $t.parse(iso8601);
},
isTime: function(elem) {
// jQuery's `is()` doesn't play well with HTML5 in IE
return $(elem).get(0).tagName.toLowerCase() === "time"; // $(elem).is("time");
}
});
// functions that can be called via $(el).timeago('action')
// init is default when no action is given
// functions are called with context of a single element
var functions = {
init: function(){
var refresh_el = $.proxy(refresh, this);
refresh_el();
var $s = $t.settings;
if ($s.refreshMillis > 0) {
this._timeagoInterval = setInterval(refresh_el, $s.refreshMillis);
}
},
update: function(time){
var parsedTime = $t.parse(time);
$(this).data('timeago', { datetime: parsedTime });
if($t.settings.localeTitle) $(this).attr("title", parsedTime.toLocaleString());
refresh.apply(this);
},
updateFromDOM: function(){
$(this).data('timeago', { datetime: $t.parse( $t.isTime(this) ?
$(this).attr("datetime") : $(this).attr("title") ) });
refresh.apply(this);
},
dispose: function () {
if (this._timeagoInterval) {
window.clearInterval(this._timeagoInterval);
this._timeagoInterval = null;
}
}
};
$.fn.timeago = function(action, options) {
var fn = action ? functions[action] : functions.init;
if(!fn){
throw new Error("Unknown function name '"+ action +"' for timeago");
}
// each over objects here and call the requested function
this.each(function(){
fn.call(this, options);
});
return this;
};
function refresh() {
var data = prepareData(this);
var $s = $t.settings;
if (!isNaN(data.datetime)) {
if ( $s.cutoff == 0 || Math.abs(distance(data.datetime)) < $s.cutoff) {
$(this).text(inWords(data.datetime));
}
}
return this;
}
function prepareData(element) {
element = $(element);
if (!element.data("timeago")) {
element.data("timeago", { datetime: $t.datetime(element) });
var text = $.trim(element.text());
if ($t.settings.localeTitle) {
element.attr("title", element.data('timeago').datetime.toLocaleString());
} else if (text.length > 0 && !($t.isTime(element) && element.attr("title"))) {
element.attr("title", text);
}
}
return element.data("timeago");
}
function inWords(date) {
return $t.inWords(distance(date));
}
function distance(date) {
return (new Date().getTime() - date.getTime());
}
// fix for IE6 suckage
document.createElement("abbr");
document.createElement("time");
}));
jQuery(document).ready(function() {
jQuery("time.timeago").timeago();
});
important <time> span!
<time class="timeago" datetime="2008-07-17T09:24:17Z" title="July 17, 2008">8 years ago</time>
which yields: 8 years ago. As time passes, the timestamps will automatically update
This is my JSONP file:
<?php
header('Content-type: application/javascript;');
header("access-control-allow-origin: *");
header("Access-Control-Allow-Methods: GET");
//db connection detils
$host = "localhost";
$user = "test";
$password = "test";
$database = "myradiostation1";
//make connection
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);
//query the database
$query = mysql_query("SELECT *, DATE_FORMAT(start, '%d/%m/%Y %H:%i:%s') AS start,
DATE_FORMAT(end, '%d/%m/%Y %H:%i:%s') AS end FROM radiostation1");
//loop through and return results
for ($x = 0, $numrows = mysql_num_rows($query); $x < $numrows; $x++) {
$row = mysql_fetch_assoc($query);
$shows[$x] = array("id" => $row["id"], "startminutes" => $row["startminutes"], "start" => $row["start"], "endminutes" => $row["endminutes"],"end" => $row["end"],"mediumname" => $row["mediumname"], "longname" => $row["longname"], "description" => $row["description"],"short_id" => $row["short_id"],"promomessage" => $row["promomessage"],"email" => $row["email"],"phonenumber" => $row["phonenumber"],"textnumber" => $row["textnumber"],"textprefix" => $row["textprefix"],"showimage" => $row["showimage"],"longdescription" => $row["longdescription"],"facebooklink" => $row["facebooklink"],"otherlink" => $row["otherlink"],"websitelink" => $row["websitelink"],"keywords" => $row["keywords"] );
}
//echo JSON to page
$response = $_GET["callback"] . "(" . json_encode($shows) . ");";
echo $response;
?>
It does work, up to a point, but getting the {"success":true,"error":"","data":{"schedule": as seen at this site before my json_encode is where I am.
However, I cannot get it to display any data in my table, although it DOES produce code on-screen when I view it at http://www.myradio1.localhost/onairschedule.php.
The actual code is stored at http://www.myradiostations.localhost/schedule.php
and the callback function works OK, one example being http://www.myradiostations.localhost/schedule.php?callback=?&name=Northern+FM and http://www.myradiostations.localhost/schedule.php?callback=?&name=Southern+FM but what do I need to do to make it change like in these examples:
this example and this example, and to generate an error message like this if no such file exists.
I'm halfway there, just need some advice on fixing my code!
Basically, what I'm trying to do... get a JSONP to work in my HTML table which will vary the content depending on the URL in my javascript file on my page, which is:
var doFades = true;
var LocalhostRadioStations = {
Schedule : {}
};
$(document).ready(function(){
LocalhostRadioStations.Schedule.days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
LocalhostRadioStations.Schedule.Show = function () {
_s = null;
_startDate = null;
_endDate = null;
this.days = LocalhostRadioStations.Schedule.days;
_selector = '';
this.setShow = function(s) {
this._s = s;
this._startDate = new Date( parseInt(s.startminutes, 10) * 1000);
this._endDate = new Date(parseInt(s.endminutes, 10) * 1000 );
};
this.getEndDate = function(){
return this._endDate;
}
this.getStartDate = function(){
return this._startDate;
}
this._getShowDay = function (){
return this.days[this.getStartDate().getDay()];
};
this._getShowUnitsTaken = function(){
// if it's the same day
return this._getEndUnits() - this._getStartUnits();
};
this._getEndUnits = function(){
if(this.getEndDate().getHours() == 0)
{
//console.log(this._s.longname +' ends at midnight');
return 48;
}
return this.getEndDate().getMinutes() !== 0 ? (this.getEndDate().getHours() * 2) : (this.getEndDate().getHours() * 2);
};
this._getStartUnits = function(){
if(this.getStartDate().getHours() == 0)
{
return 0;
}
return this.getStartDate().getMinutes() !== 0 ? (this.getStartDate().getHours() * 2) : (this.getStartDate().getHours() * 2);
};
this.getCellPositions = function() {
return {
'start' : this.getStartDate(),
'end' : this.getEndDate(),
'colIndex' : this.getStartDate().getDay() + 2,
'startUnits' : this._getStartUnits(),
'endUnits' : this._getEndUnits(),
'unitsTaken' : this._getShowUnitsTaken()
}
};
this.pad = function(number){
return number < 10 ? '0'+number : number;
};
// return the table cell html.
this.toHtml = function () {
var d = new Date();
var units = this._getStartUnits();
var rowspan = this._getShowUnitsTaken();
var desc = this._s.description;
var name = this._s.longname;
var starttime = this.pad(this.getStartDate().getHours()) + ':' + this.pad(this.getStartDate().getMinutes());
var endtime = this.pad(this.getEndDate().getHours()) + ':' + this.pad(this.getEndDate().getMinutes());
var site = this._s.websitelink;
var cls = this.isActive() ? 'current-program' : '';
var isToday = this.getStartDate().getDay() === d.getDay() ? 'active-program' : '';
var html = '<td class="schedule-show ' + isToday + ' ' + cls + '" rowspan="' + rowspan + '" data-start="' + this.getStartDate() + '" data-end="' + this.getEndDate() + '">';
html += '<div>';
html += '' + name + '';
html += '</div>';
if(doFades)
{
html += '<div class="schedule_details clearfix" style="display:none;">';
html += '<img width="105px" height="105px" alt="' + desc + '" src="' + this._s.showimage + '">';
html += '<strong>' + name + '</strong>';
html += '<p>' + desc + '</p>';
html += '<span>' + starttime + ' - ' + endtime +'</span>';
html += '</div>';
}
html += '</td>';
return html;
};
this.setTableSelector = function(sel){
this._selector = sel;
};
// check if we should add the active class.
this.isActive = function(){
var t = new Date();
return t >= this.getStartDate() && t <= this.getEndDate();
};
};
LocalhostRadioStations.Schedule.ScheduleGen = function(){
return {
insertShow : function(show) {
var p = show.getCellPositions();
$('tr#units-' + p.startUnits).append(show.toHtml());
},
init : function (stationName){
var self = this;
// load the schedule.
$.getJSON('http://www.myradiostations.localhost/schedule.php?callback=?&name=', {
name: 'Northern FM'
}, function(json){
// loop each show and append to our giant table.
// this is well sick.
if(json.success === false)
{
$('.content-inner table').remove();
$('<div>errors</div>').appendTo('.content-inner');
}
else
{
var currentDay = '';
var day = 0;
// highlight the current time..
var d = new Date();
var weekStart = new Date();
weekStart.setDate(d.getDate()-6-(d.getDay()||7));
$.each(json.data.schedule, function(i, broadcast){
var dStart = new Date( parseInt(broadcast.startminutes, 10) * 1000);
var dEnd = new Date(parseInt(broadcast.endminutes, 10) * 1000 );
/*// transform to a show object defined above, if the show spans 2 days we create two show objects.
// IF THE SHOW STARTS/ENDS AT MIDNIGHT, DON'T SPLIT IT.
if(dStart.getHours() !== 0 && dEnd.getHours() !== 0 && dStart.getDate() != dEnd.getDate())
{
var showOne = new LocalhostRadioStations.Schedule.Show();
showOne.setShow(broadcast);
// set to midnight
showOne.getEndDate().setHours(0);
showOne.getEndDate().setMinutes(dStart.getMinutes());
// append first half of show.
self.insertShow(showOne);
// handle second half.
var showTwo = new LocalhostRadioStations.Schedule.Show();
showTwo.setShow(broadcast);
showTwo.getStartDate().setDate(showTwo.getStartDate().getDate() + 1);
showTwo.getStartDate().setHours(0);
showTwo.getStartDate().setMinutes(dEnd.getMinutes());
//console.log('2nd Half Start: ' + showTwo.getStartDate());
//console.log('2nd Half End: ' + showTwo.getEndDate());
self.insertShow(showTwo);
}
else
{*/
var show = new LocalhostRadioStations.Schedule.Show();
show.setShow(broadcast);
show.setTableSelector('table#schedule');
// add the show to the table. Thankfully the order these come out the API means they get added
// in the right place. So don't change the schedule builder code!
self.insertShow(show);
//}
});
var days = LocalhostRadioStations.Schedule.days;
// apply the current day / time classes
$('th:contains('+ days[d.getDay()]+')').addClass('active');
$('td.time').each(function(i, cell){
// get the value, convert to int.
var hours = $(cell).html().split(':')[0];
// compare the hours with now, add class if matched.
if(parseInt(hours, 10) === d.getHours())
{
$(cell).addClass('current_time');
}
});
}
if(doFades)
{
// apply events to show info fade in / out.
$('td.schedule-show').hover(function(){
$(this).find('.schedule_details').fadeIn('fast');
}, function(){
$(this).find('.schedule_details').fadeOut('fast');
});
}
});
}
};
}();
LocalhostRadioStations.Schedule.ScheduleGen.init(twittiName);
});
It should change the schedule according to the JSONP, but what do I do to fix it?
Basically, I am trying to make my own localhost version of http://radioplayer.bauerradio.com/schedule.php?callback=&name=Rock+FM and its JSON / JSONP (I am not sure exactly what type the original is, but then again the site is experimental and on a .localhost domain) for testing purposes where the content is taken from the database, and changes according to station name, e.g. http://radioplayer.bauerradio.com/schedule.php?callback=&name=Metro+Radio and http://radioplayer.bauerradio.com/schedule.php?callback=&name=Forth+One etc.
Edit: The full code for my page can be seen at http://pastebin.com/ENhR6Q9j
I'm not sure exactly what's missing, but from the code you gave so far, I made a jsfiddle:
Demo
I modified some things to make it work (mostly appending stuff), because I don't know your original HTML file. But I also made some changes based on what you say you wanted. First of all I modified your $.getJSON call to be something like:
$.getJSON('http://radioplayer.bauerradio.com/schedule.php?callback=?', {
name: stationName //stationName is from the argument passed
}, function(json){...})
Which should give back the station based on what is passed to
LocalhostRadioStations.Schedule.ScheduleGen.init(twittiName);
To make it more interesting, I also added a bit of code that reads from the url. In this case if you go to the page with a domain.htm/page?Northern FM it will read the text after the ? and put it in twittiName.
var twittiName="Rock FM"; //default station
if(window.location.search){
twittiName=window.location.search.substring(1) //or window.location.hash
}
Tried to look for other stations that might be on your publics site, but so far I could only test with "?Rock+FM". But does mean you can show the errors, which your code can handle as it is.
?Rock+FM
?Random Name
So it seems that your code mostly works but do comment if I have missed anything.
I am programming the website for my church hockey league, and I am trying to make a page with live updates. I am currently trying a setInterval() to signal php to update the time.txt which the live page can draw the time from. So the update.html has the time on it, this page sends the time to a php doc with a get function which writes the time to time.txt, then live.html gets the time every 5 secs with a setInterval(). In that 5 secs live.html keeps its own time, but needs to check every 5 for pauses or time changes.
The problem is this: the server cant handle updating time.txt every 2.5 seconds so I need a simpler method that doesn't require me to update time.txt every 2.5, but live.html still can get the time, pauses, and time changes.
Any help please.
Here is update.html
$('#play').click(function(){
if(pause == true){
$('#play').attr('src',"mup/pause.jpg");
$.get("mup/postt.php", {text: "11"});
pause = false;
} else {
$('#play').attr('src',"mup/play.jpg");
$.get("mup/postt.php", {text: "09"});
pause = true;
}
});
function updatet(){
if(sec < 10){
if(min < 10){
var clientmsg = "0" + min + ":0" + sec;
} else {
var clientmsg = min + ":0" + sec;
}
} else {
if(min < 10){
var clientmsg = "0" + min + ":" + sec;
} else {
var clientmsg = min + ":" + sec;
}
}
$.get("mup/postt.php", {text: clientmsg});
}
setInterval (timer, 1000);
setInterval (updatet, 3000);
all the variables are defined at the beginning of the doc.
here is live.html
function timer() {
if(stop == true){
$("#time").html("<h5>Game Stopped</h5>");
} else {
sec = sec-1;
if(sec <= -1){
sec = 59;
min = min-1;
if(min <= -1){
sec=0;
min=0;
}
}
$("#time").html("\<h2\>"+min+":"+sec+"\</h2\>");
}
}
loadLog() {
$.ajax({
url: "mup/time.txt",
cache: false,
success: function(html){
var min = html.charAt(0).concat(html.charAt(1));
var sec = html.charAt(3).concat(html.charAt(4));
var time = min + ":" + sec;
if(time == timel){
stop = true;
} else {
stop = false;
}
timel = time;
},
});
}
setInterval (loadLog, 5000);
setInterval (timer, 1000);
and at the beginning of the doc all variable were defined with timel and time being different. Post.php just puts the sent stuff onto the doc, so time.txt would look like "06:08" or whatever.aa
I need to implement a custom info window on my google map.
I found this custom info window here : Creating custom info windows in Google Maps
I used the code provided by Googles Developers page , to create the map and everything worked great with the typical info window. Now i changed my code to try and implement the above custom info window , called "infobox" . However it is not working. I am not sure if i used the code correctly.
This is my code for the google map. Note the infoBox function , is the custom info window.
<!DOCTYPE html >
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>PHP/MySQL and Google Maps Example</title>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
//<![CDATA[
var customIcons = {
restaurant: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
bar: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(47.6145, -122.3418),
zoom: 15,
mapTypeId: 'roadmap'
});
//var infoWindow = new google.maps.InfoWindow;
infobox = new InfoBox({ width: "260px" }); // initialize
// Change this depending on the name of your PHP file
downloadUrl("testing.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infobox, html);
}
});
}
function bindInfoWindow(marker, map, infobox, html) {
google.maps.event.addListener(marker, 'click', function() {
//infoWindow.setContent(html);
//infoWindow.open(map, marker);
infobox.setContent(html); // set content
infobox.open(map, marker); // open on the marker
infobox.draw(); // to redraw if infobox size changed
//infobox.close();
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function InfoBox(opt_opts) {
opt_opts = opt_opts || {};
this.imgPath='img/infoBox/';
google.maps.OverlayView.apply(this, arguments);
// Standard options (in common with google.maps.InfoWindow):
this.content_ = opt_opts.content || "";
this.maxWidth_ = opt_opts.maxWidth || 0;
this.pixelOffset_ = opt_opts.pixelOffset || new google.maps.Size(0, 0);
this.position_ = opt_opts.position || new google.maps.LatLng(0, 0);
this.zIndex_ = opt_opts.zIndex || null;
// Additional options (unique to InfoBox):
this.boxStyle_ = opt_opts || {};
this.infoBoxClearance_ = new google.maps.Size(1, 1);
this.isHidden_ = opt_opts.isHidden || false;
this.pane_ = "overlayMouseTarget";
this.enableEventPropagation_ = opt_opts.enableEventPropagation || false;
this.div_ = null;
this.closeListener_ = null;
this.eventListener1_ = null;
this.eventListener2_ = null;
this.eventListener3_ = null;
this.contextListener_ = null;
this.fixedWidthSet_ = null;
}
/* InfoBox extends OverlayView in the Google Maps API v3. */
InfoBox.prototype = new google.maps.OverlayView();
// Creates the DIV representing the InfoBox. #private
InfoBox.prototype.createInfoBoxDiv_ = function(){
var bw, me = this;
// This handler prevents an event in the InfoBox from being passed on to the map.
var cancelHandler = function (e){ e.cancelBubble = true; if (e.stopPropagation) e.stopPropagation(); };
// This handler ignores the current event in the InfoBox and conditionally prevents the event from being passed on to the map. It is used for the contextmenu event.
var ignoreHandler = function (e) { e.returnValue = false; if (e.preventDefault) e.preventDefault(); if (!me.enableEventPropagation_){ e.cancelBubble = true; if (e.stopPropagation) e.stopPropagation(); } };
if (!this.div_){ // first time create
this.div_ = document.createElement("div");
this.div_.className = 'infowindow';
this.setBoxStyle_();
// Apply required styles:
if (this.zIndex_ !== null) this.div_.style.zIndex = this.zIndex_;
this.div_.contentDiv = document.createElement('div');
this.div_.contentDiv.className = 'infowindow-wrapper';
this.div_.contentDiv.innerHTML = this.content_;
this.div_.innerHTML = '<img src="'+this.imgPath+'close.png" align="right" class="infowindow-close">';
this.div_.appendChild(this.div_.contentDiv);
// Add the InfoBox DIV to the DOM
this.getPanes()[this.pane_].appendChild(this.div_);
this.addClickHandler_();
if (this.div_.style.width) this.fixedWidthSet_ = true;
else {
if (this.maxWidth_ !== 0 && this.div_.offsetWidth > this.maxWidth_) {
this.div_.style.width = this.maxWidth_;
this.fixedWidthSet_ = true;
}
else { // The following code is needed to overcome problems with MSIE
bw = this.getBoxWidths_();
this.div_.style.width = (this.div_.offsetWidth - bw.left - bw.right) + "px";
this.fixedWidthSet_ = false;
}
}
//add shadow
this.shadowContainer_ = document.createElement("div");
this.shadowContainer_.style.position='absolute';
this.shadowContainer_.style.display = 'block';
this.shadowContainer_.style.zIndex='-99';
this.getPanes()['overlayShadow'].appendChild(this.shadowContainer_);
this.shadow = document.createElement('img');
this.shadow.src = this.imgPath+'shadow.png';
this.shadow.style.position='absolute';
this.shadow.style.width = '100%';
this.shadow.style.height = '100%';
this.shadowContainer_.appendChild(this.shadow);
if (!this.enableEventPropagation_) {
this.eventListener1_ = google.maps.event.addDomListener(this.div_.contentDiv, "mousedown", cancelHandler);
this.eventListener2_ = google.maps.event.addDomListener(this.div_, "click", function(e){
e.cancelBubble = true; if (e.stopPropagation) e.stopPropagation();
if (GoogleMap && GoogleMap.closeEditors) GoogleMap.closeEditors(true);
});
//this.eventListener3_ = google.maps.event.addDomListener(this.div_, "dblclick", cancelHandler);
try{ this.eventListener3_ = google.maps.event.addDomListener(this.div_, "dblclick", facilityEditor);}catch(e){}
}
this.contextListener_ = google.maps.event.addDomListener(this.div_, "contextmenu", ignoreHandler);
var contentWidth = parseInt(this.div_.style.width.slice(0,-2)), contentHeight = this.div_.offsetHeight;
this.wrapperParts = { //create an object to reference each image
tl:{l:-26, t:-26, w:26, h:26},
t:{l:0, t:-26, w:contentWidth, h:26},
tr:{l:contentWidth, t:-26, w:26, h:26},
l:{l:-26, t:0, w:26, h:contentHeight},
r:{l:contentWidth, t:0, w:26, h: contentHeight },
bl:{l:-26, t:contentHeight, w:26, h:26},
b:{l:0, t:contentHeight, w:contentWidth, h:26},
br:{l:contentWidth, t:contentHeight, w:26, h:26},
p:{l:contentWidth-170, t:contentHeight+18, w:92, h:77 }
}
for (i in this.wrapperParts){ //create the image DOM objects
var img = document.createElement('img');
img.src = this.imgPath + i + '.png'; //load the image from your local image directory based on the property name of the wrapperParts object
img.style.position='absolute'; //set the appropriate positioning attributes
img.style.top=this.wrapperParts[i].t+'px';
img.style.left=this.wrapperParts[i].l+'px';
img.style.width=this.wrapperParts[i].w+'px';
img.style.height=this.wrapperParts[i].h+'px';
this.div_.appendChild(img);
this.wrapperParts[i].img = img;
}
google.maps.event.trigger(this, "domready");
}
else {
var contentWidth = parseInt(this.div_.style.width.slice(0,-2)), contentHeight = this.div_.offsetHeight, twp=this.wrapperParts;
twp.t.img.style.width=contentWidth+'px';
twp.tr.img.style.left=contentWidth+'px';
twp.l.img.style.height=contentHeight+'px';
twp.r.img.style.left=contentWidth+'px';
twp.r.img.style.height=contentHeight+'px';
twp.bl.img.style.top=contentHeight+'px';
twp.b.img.style.top=contentHeight+'px';
twp.b.img.style.width=contentWidth+'px';
twp.br.img.style.left=contentWidth+'px';
twp.br.img.style.top=contentHeight+'px';
twp.p.img.style.left=(contentWidth-170)+'px';
twp.p.img.style.top=(contentHeight+18)+'px';
}
};
InfoBox.prototype.addClickHandler_=function(){
this.closeListener_ = google.maps.event.addDomListener(this.div_.firstChild, 'click', this.getCloseClickHandler_());
try{ this.eventListener3_ = google.maps.event.addDomListener(this.div_, "dblclick", facilityEditor);}catch(e){}
};
InfoBox.prototype.getCloseClickHandler_=function () { var me = this; return function(){ me.close(); google.maps.event.trigger(me, "closeclick"); }; };
//Pans the map so that the InfoBox appears entirely within the map's visible area. #private
InfoBox.prototype.panBox_ = function (disablePan) {
if (!disablePan) {
var map = this.getMap();
var bounds = map.getBounds();
// The degrees per pixel
var mapDiv = map.getDiv();
var mapWidth = mapDiv.offsetWidth;
var mapHeight = mapDiv.offsetHeight;
var boundsSpan = bounds.toSpan();
var longSpan = boundsSpan.lng();
var latSpan = boundsSpan.lat();
var degPixelX = longSpan / mapWidth;
var degPixelY = latSpan / mapHeight;
// The bounds of the map
var mapWestLng = bounds.getSouthWest().lng();
var mapEastLng = bounds.getNorthEast().lng();
var mapNorthLat = bounds.getNorthEast().lat();
var mapSouthLat = bounds.getSouthWest().lat();
// The bounds of the box
var position = this.position_;
var iwOffsetX = this.pixelOffset_.width;
var iwOffsetY = this.pixelOffset_.height;
var padX = this.infoBoxClearance_.width;
var padY = this.infoBoxClearance_.height;
var iwWestLng = position.lng() + (iwOffsetX - padX - this.div_.contentDiv.offsetWidth/2 - 450) * degPixelX; // 450 - move right - from under the sidebar
var iwEastLng = position.lng() + (iwOffsetX + padX + 220) * degPixelX;
var iwNorthLat = position.lat() - (iwOffsetY - padY - this.div_.contentDiv.offsetHeight - 180) * degPixelY; // 180 - move down - from under the top search bar
var iwSouthLat = position.lat() - (iwOffsetY + padY + 20) * degPixelY;
// Calculate center shift
var shiftLng = (iwWestLng < mapWestLng ? mapWestLng - iwWestLng : 0) + (iwEastLng > mapEastLng ? mapEastLng - iwEastLng : 0);
var shiftLat = (iwNorthLat > mapNorthLat ? mapNorthLat - iwNorthLat : 0) + (iwSouthLat < mapSouthLat ? mapSouthLat - iwSouthLat : 0);
if (!(shiftLat === 0 && shiftLng === 0)) {
// Move the map to the new shifted center.
var c = map.getCenter();
map.setCenter(new google.maps.LatLng(c.lat() - shiftLat, c.lng() - shiftLng));
}
}
};
// Sets the style of the InfoBox. #private
InfoBox.prototype.setBoxStyle_ = function () {
var i;
var boxStyle = this.boxStyle_;
for (i in boxStyle) if (boxStyle.hasOwnProperty(i)) this.div_.style[i] = boxStyle[i];
// Fix up opacity style for benefit of MSIE:
if (typeof this.div_.style.opacity !== "undefined") this.div_.style.filter = "alpha(opacity=" + (this.div_.style.opacity * 100) + ")";
};
// Get the widths of the borders of the InfoBox. #private; #return {Object} widths object (top, bottom left, right)
InfoBox.prototype.getBoxWidths_ = function () {
var computedStyle;
var bw = {top: 0, bottom: 0, left: 0, right: 0};
var box = this.div_;
if (document.defaultView && document.defaultView.getComputedStyle) {
computedStyle = box.ownerDocument.defaultView.getComputedStyle(box, "");
if (computedStyle) {
// The computed styles are always in pixel units (good!)
bw.top = parseInt(computedStyle.borderTopWidth, 10) || 0;
bw.bottom = parseInt(computedStyle.borderBottomWidth, 10) || 0;
bw.left = parseInt(computedStyle.borderLeftWidth, 10) || 0;
bw.right = parseInt(computedStyle.borderRightWidth, 10) || 0;
}
}
else if (document.documentElement.currentStyle) { // MSIE
if (box.currentStyle) {
// The current styles may not be in pixel units, but assume they are (bad!)
bw.top = parseInt(box.currentStyle.borderTopWidth, 10) || 0;
bw.bottom = parseInt(box.currentStyle.borderBottomWidth, 10) || 0;
bw.left = parseInt(box.currentStyle.borderLeftWidth, 10) || 0;
bw.right = parseInt(box.currentStyle.borderRightWidth, 10) || 0;
}
}
return bw;
};
// Invoked when <tt>close</tt> is called. Do not call it directly.
InfoBox.prototype.onRemove = function () {
if (this.div_) {
this.shadowContainer_.parentNode.removeChild(this.shadowContainer_);
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
}
};
//Draws the InfoBox based on the current map projection and zoom level.
InfoBox.prototype.draw = function(){
this.createInfoBoxDiv_();
var pixPosition = this.getProjection().fromLatLngToDivPixel(this.position_);
this.div_.style.left = (pixPosition.x - this.div_.offsetWidth + 180 ) + "px";
this.div_.style.top = (pixPosition.y - this.div_.offsetHeight - 125) + "px";
this.shadowContainer_.style.left = (pixPosition.x - this.div_.offsetWidth + 220 ) + 'px';
this.shadowContainer_.style.top = (pixPosition.y - this.div_.offsetHeight - 130) + "px";
this.shadowContainer_.style.height = (this.div_.offsetHeight+100 ) + 'px';
this.shadowContainer_.style.width = (this.div_.offsetWidth+100 ) + 'px';
if (this.isHidden_) this.div_.style.visibility = 'hidden';
else this.div_.style.visibility = "visible";
this.panBox_();
};
InfoBox.prototype.setContent = function(content){
this.content_ = content;
if (this.div_){// Odd code required to make things work with MSIE.
this.div_.style.visibility='hidden'
if (!this.fixedWidthSet_) this.div_.style.width = "";
this.div_.contentDiv.innerHTML = content;
// Perverse code required to make things work with MSIE. (Ensures the close box does, in fact, float to the right.)
if (!this.fixedWidthSet_){ this.div_.style.width = this.div_.offsetWidth + "px"; this.div_.contentDiv.innerHTML = content; }
this.addClickHandler_();
}
// This event is fired when the content of the InfoBox changes. #name InfoBox#content_changed; #event
google.maps.event.trigger(this, "content_changed");
};
//Sets the geographic location of the InfoBox. #param {LatLng} latlng
InfoBox.prototype.setPosition = function (latlng) {
this.position_ = latlng;
if (this.div_) this.draw();
//This event is fired when the position of the InfoBox changes. #name InfoBox#position_changed; #event
google.maps.event.trigger(this, "position_changed");
};
InfoBox.prototype.getContent = function () { return this.content_; }; //Returns the content of the InfoBox. #returns {string}
InfoBox.prototype.show = function (){ this.isHidden_ = false; this.div_.style.visibility = "visible"; }; //Shows the InfoBox.
InfoBox.prototype.hide = function (){ this.isHidden_ = true; this.div_.style.visibility = "hidden"; }; //Hides the InfoBox.
InfoBox.prototype.open = function (map, anchor) {
if (anchor) this.position_ = anchor.getPosition();
this.setMap(map);
};
//Removes the InfoBox from the map.
InfoBox.prototype.close = function (){
if (this.closeListener_) {
google.maps.event.removeListener(this.closeListener_);
this.closeListener_ = null;
}
if (this.contextListener_) {
google.maps.event.removeListener(this.contextListener_);
this.contextListener_ = null;
}
this.setMap(null);
};
function doNothing() {}
//]]>
</script>
</head>
<body onload="load()">
<div id="map" style="width: 100%; height: 600px"></div>
</body>
</html>
In the above code , i just changed everything mentioning infowindow , with the new infobox , and added the new function InfoBox(). However i am not sure , how and where i should use the
infobox.setContent(html); // set content
infobox.open(map, marker); // open on the marker
infobox.draw(); // to redraw if infobox size changed
infobox.close();
Where should i use the infobox.close() function? In my code i commented this line , cause i didnt know how to use it.
I believe your missing a position: absolute style for the infobox and also background color if it's not set in the css (originally I had that set in css, that's why it worked for me :-))
look for this line in your code:
this.div_.className = 'infowindow';
and add this below:
this.div_.style.position = 'absolute';
this.div_.style.backgroundColor = '#fff';
You should also add some images for the infobox as the whole box is build based on the images (you'll find references in the script).