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>
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>
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
position absolute doesn't work in mozilla. For jquery calender I used position:absolute for a div it seems to work all except mozilla in windows. When I remove the position:absolute it will work in windows firefox but only showing alternate months in all other browsers
jquery is
var CalendarEightysix = new Class({
Implements: Options,
options: {
'slideDuration': 500,
'fadeDuration': 200,
'toggleDuration': 200,
'fadeTransition': Fx.Transitions.linear,
'slideTransition': Fx.Transitions.Quart.easeOut,
'prefill': true,
'defaultDate': null,
'linkWithInput': true,
'theme': 'default',
'defaultView': 'month',
'startMonday': false,
'alwaysShow': false,
'injectInsideTarget': false,
'format': '%n/%d/%Y',
'alignX': 'right',
'alignY': 'ceiling',
'offsetX': 0,
'offsetY': 0,
'draggable': false,
'pickable': true,
'toggler': null,
'pickFunction': $empty,
'disallowUserInput': false,
'minDate': null,
'maxDate': null,
'excludedWeekdays': null,
'excludedDates': null,
'createHiddenInput': false,
'hiddenInputName': 'date',
'hiddenInputFormat': '%t'
},
initialize: function(target, options) {
this.setOptions(options);
this.target = $(target);
this.transitioning = false;
//Extend Date with unix timestamp parser
Date.defineParser({
re: /^[0-9]{10}$/,
handler: function(bits) { return new Date.parse('Jan 01 1970').set('seconds', bits[0]); }
});
//Selected date
if($defined(this.options.defaultDate)) this.selectedDate = new Date().parse(this.options.defaultDate).clearTime();
else if(this.options.linkWithInput && $chk(this.target.get('value'))) this.selectedDate = new Date().parse(this.target.get('value')).clearTime();
if(!$defined(this.selectedDate) || !this.selectedDate.isValid()) this.selectedDate = new Date();
this.viewDate = this.selectedDate.clone().set('date', 1).clearTime();
//Base
var innerHtml = '<div class="wrapper"><div class="header"><div class="arrow-left"></div><div class="arrow-right"></div><div class="label clickable"></div></div>'+
'<div class="body"><div class="inner"><div class="container a"></div><div class="container b"></div></div></div><div class="footer"></div></div>';
this.element = new Element('div', { 'class': 'calendar-eightysix', 'html': innerHtml, 'style': 'display: '+ (this.options.alwaysShow ? 'block' : 'none') }).addClass(this.options.theme);
if(this.options.injectInsideTarget) this.element.injectBottom(this.target);
else {
this.element.injectBottom($(document.body));
this.position();
window.addEvent('resize', this.position.bind(this));
}
this.currentContainer = this.element.getElement('.container.a').setStyle('z-index', 999);
this.tempContainer = this.element.getElement('.container.b').setStyle('z-index', 998);
//Header
this.header = this.element.getElement('.header');
this.label = this.header.getElement('.label');
this.arrowLeft = this.header.getElement('.arrow-left');
this.arrowRight = this.header.getElement('.arrow-right');
this.label.addEvent('click', this.levelUp.bind(this));
this.arrowLeft.addEvent('click', this.slideLeft.bind(this));
this.arrowRight.addEvent('click', this.slideRight.bind(this));
//Date range
if($defined(this.options.minDate)) {
this.options.minDate = Date.parse(this.options.minDate).clearTime();
if(!this.options.minDate.isValid()) this.options.minDate = null;
}
if($defined(this.options.maxDate)) {
this.options.maxDate = Date.parse(this.options.maxDate).clearTime();
if(!this.options.maxDate.isValid()) this.options.maxDate = null;
}
//Excluded dates
if($defined(this.options.excludedDates)) {
var excludedDates = [];
this.options.excludedDates.each(function(date) {
excludedDates.include(this.format(new Date().parse(date).clearTime(), '%t'));
}.bind(this));
this.options.excludedDates = excludedDates;
}
//Dragger
if(this.options.draggable && !this.options.injectInsideTarget) {
this.header.addClass('dragger');
new Drag(this.element, { 'handle': this.header });
}
//Hidden input
if(this.options.createHiddenInput) {
this.hiddenInput = new Element('input', { 'type': 'hidden', 'name': this.options.hiddenInputName }).injectAfter(this.target);
}
//Prefill date
if(this.options.prefill) this.pick();
//Link with input
if(!this.options.disallowUserInput && this.options.linkWithInput && this.target.get('tag') == 'input') {
this.target.addEvent('keyup', function() {
this.setDate(this.target.get('value'), false);
}.bind(this));
}
//Disallow input
if(this.options.disallowUserInput && this.target.get('tag') == 'input')
this.target.addEvents({ 'keydown': ($lambda(false)), 'contextmenu': ($lambda(false)) });
//Toggler
if($defined(this.options.toggler)) this.options.toggler = $(this.options.toggler);
//Show / hide events
($defined(this.options.toggler) ? this.options.toggler : this.target).addEvents({
'focus': this.show.bind(this), 'click': this.show.bind(this)
});
if(!this.options.alwaysShow) document.addEvent('mousedown', this.outsideClick.bind(this));
MooTools.lang.addEvent('langChange', function() { this.render(); this.pick(); }.bind(this));
//View
this.view = this.options.defaultView;
this.render();
},
render: function() {
this.currentContainer.empty();
switch(this.view) {
case 'decade': this.renderDecade(); break;
case 'year': this.renderYear(); break;
default: this.renderMonth();
}
},
renderMonth: function() {
this.view = 'month';
this.currentContainer.empty().addClass('month');
if(this.options.pickable) this.currentContainer.addClass('pickable');
var lang = MooTools.lang.get('Date'), weekdaysCount = this.viewDate.format('%w') - (this.options.startMonday ? 1 : 0);
if(weekdaysCount == -1) weekdaysCount = 6;
var today = new Date();
//Label
this.label.set('html', lang.months[this.viewDate.get('month')] +' '+ this.viewDate.format('%Y'));
//Day label row
var row = new Element('div', { 'class': 'row' }).injectBottom(this.currentContainer);
for(var i = (this.options.startMonday ? 1 : 0); i < (this.options.startMonday ? 8 : 7); i++) {
var day = new Element('div', { 'html': lang.days[this.options.startMonday && i == 7 ? 0 : i] }).injectBottom(row);
day.set('html', day.get('html').substr(0, 2));
}
//Add days for the beginning non-month days
row = new Element('div', { 'class': 'row' }).injectBottom(this.currentContainer);
y = this.viewDate.clone().decrement('month').getLastDayOfMonth();
for(var i = 0; i < weekdaysCount; i++) {
this.injectDay(row, this.viewDate.clone().decrement('month').set('date', y - (weekdaysCount - i) + 1), true);
}
//Add month days
for(var i = 1; i <= this.viewDate.getLastDayOfMonth(); i++) {
this.injectDay(row, this.viewDate.clone().set('date', i));
if(row.getChildren().length == 7) {
row = new Element('div', { 'class': 'row' }).injectBottom(this.currentContainer);
}
}
//Add outside days
var y = 8 - row.getChildren().length, startDate = this.viewDate.clone().increment('month').set('date', 1);
for(var i = 1; i < y; i++) {
this.injectDay(row, startDate.clone().set('date', i), true);
}
//Always have six rows
for(var y = this.currentContainer.getElements('.row').length; y < 7; y++) {
row = new Element('div', { 'class': 'row' }).injectBottom(this.currentContainer);
for(var z = 0; z < 7; z++) {
this.injectDay(row, startDate.clone().set('date', i), true);
i++;
}
}
this.renderAfter();
},
//Used by renderMonth
injectDay: function(row, date, outside) {
today = new Date();
var day = new Element('div', { 'html': date.get('date') }).injectBottom(row);
day.date = date;
if(outside) day.addClass('outside');
if(($defined(this.options.minDate) && this.format(this.options.minDate, '%t') > this.format(date, '%t')) ||
($defined(this.options.maxDate) && this.format(this.options.maxDate, '%t') < this.format(date, '%t')) ||
($defined(this.options.excludedWeekdays) && this.options.excludedWeekdays.contains(date.format('%w').toInt())) ||
($defined(this.options.excludedDates) && this.options.excludedDates.contains(this.format(date, '%t'))))
day.addClass('non-selectable');
else if(this.options.pickable) day.addEvent('click', this.pick.bind(this));
if(date.format('%x') == today.format('%x')) day.addClass('today');
if(date.format('%x') == this.selectedDate.format('%x')) day.addClass('selected');
},
renderYear: function() {
this.view = 'year';
this.currentContainer.addClass('year-decade');
var today = new Date(), lang = MooTools.lang.get('Date').months;
//Label
this.label.set('html', this.viewDate.format('%Y'));
var row = new Element('div', { 'class': 'row' }).injectBottom(this.currentContainer);
for(var i = 1; i < 13; i++) {
var month = new Element('div', { 'html': lang[i - 1] }).injectBottom(row);
month.set('html', month.get('html').substr(0, 3)); //Setting and getting the innerHTML takes care of html entity problems (e.g. [M&a]uml;r => [Mär]z)
var iMonth = this.viewDate.clone().set('month', i - 1);
month.date = iMonth;
if(($defined(this.options.minDate) && this.format(this.options.minDate.clone().set('date', 1), '%t') > this.format(iMonth, '%t')) ||
($defined(this.options.maxDate) && this.format(this.options.maxDate.clone().set('date', 1), '%t') < this.format(iMonth, '%t')))
month.addClass('non-selectable');
else month.addEvent('click', this.levelDown.bind(this));
if(i - 1 == today.get('month') && this.viewDate.get('year') == today.get('year')) month.addClass('today');
if(i - 1 == this.selectedDate.get('month') && this.viewDate.get('year') == this.selectedDate.get('year')) month.addClass('selected');
if(!(i % 4) && i != 12) row = new Element('div', { 'class': 'row' }).injectBottom(this.currentContainer);
}
this.renderAfter();
},
renderDecade: function() {
this.label.removeClass('clickable');
this.view = 'decade';
this.currentContainer.addClass('year-decade');
var today = new Date();
var viewYear, startYear;
viewYear = startYear = this.viewDate.format('%Y').toInt();
while(startYear % 12) startYear--;
//Label
this.label.set('html', startYear +' '+ (startYear + 11));
var row = new Element('div', { 'class': 'row' }).injectBottom(this.currentContainer);
for(var i = startYear; i < startYear + 12; i++) {
var year = new Element('div', { 'html': i }).injectBottom(row);
var iYear = this.viewDate.clone().set('year', i);
year.date = iYear;
if(($defined(this.options.minDate) && this.options.minDate.get('year') > i) ||
($defined(this.options.maxDate) && this.options.maxDate.get('year') < i)) year.addClass('non-selectable');
else year.addEvent('click', this.levelDown.bind(this));
if(i == today.get('year')) year.addClass('today');
if(i == this.selectedDate.get('year')) year.addClass('selected');
if(!((i + 1) % 4) && i != startYear + 11) row = new Element('div', { 'class': 'row' }).injectBottom(this.currentContainer);
}
this.renderAfter();
},
renderAfter: function() {
//Iterate rows and add classes and remove navigation if nessesary
var rows = this.currentContainer.getElements('.row');
for(var i = 0; i < rows.length; i++) {
rows[i].set('class', 'row '+ ['a', 'b', 'c', 'd', 'e', 'f', 'g'][i] +' '+ (i % 2 ? 'even' : 'odd')).getFirst().addClass('first');
rows[i].getLast().addClass('last');
if(i == (this.view == 'month' ? 1 : 0) && $defined(this.options.minDate) && this.format(this.options.minDate, '%t') >= this.format(rows[i].getFirst().date, '%t'))
this.arrowLeft.setStyle('visibility', 'hidden');
if(i == rows.length - 1 && $defined(this.options.maxDate)) {
if((this.view == 'month' && this.format(this.options.maxDate, '%t') <= this.format(rows[i].getLast().date, '%t')) ||
(this.view == 'year' && this.format(this.options.maxDate, '%t') <= this.format(rows[i].getLast().date.clone().increment('month'), '%t')) ||
(this.view == 'decade' && this.format(this.options.maxDate, '%t') <= this.format(rows[i].getLast().date.clone().increment('year'), '%t')))
this.arrowRight.setStyle('visibility', 'hidden');
}
};
},
slideLeft: function() {
this.switchContainers();
//Render new view
switch(this.view) {
case 'month': this.viewDate.decrement('month'); break;
case 'year': this.viewDate.decrement('year'); break;
case 'decade': this.viewDate.set('year', this.viewDate.get('year') - 12); break;
}
this.render();
//Tween the new view in and old view out
this.currentContainer.set('tween', { 'duration': this.options.slideDuration, 'transition': this.options.slideTransition }).tween('left', [-this.currentContainer.getWidth(), 0]);
this.tempContainer.set('tween', { 'duration': this.options.slideDuration, 'transition': this.options.slideTransition }).tween('left', [0, this.tempContainer.getWidth()]);
},
slideRight: function() {
this.switchContainers();
//Render new view
switch(this.view) {
case 'month': this.viewDate.increment('month'); break;
case 'year': this.viewDate.increment('year'); break;
case 'decade': this.viewDate.set('year', this.viewDate.get('year') + 12); break;
}
this.render();
//Tween the new view in and old view out
this.currentContainer.set('tween', { 'duration': this.options.slideDuration, 'transition': this.options.slideTransition }).tween('left', [this.currentContainer.getWidth(), 0]);
this.tempContainer.set('tween', { 'duration': this.options.slideDuration, 'transition': this.options.slideTransition }).tween('left', [0, -this.currentContainer.getWidth()]);
},
levelDown: function(e) {
if(this.transitioning) return;
this.switchContainers();
this.viewDate = e.target.date;
//Render new view
switch(this.view) {
case 'year': this.renderMonth(); break;
case 'decade': this.renderYear(); break;
}
//Tween the new view in and old view out
this.transitioning = true;
this.currentContainer.set('tween', { 'duration': this.options.fadeDuration, 'transition': this.options.fadeTransition,
'onComplete': function() { this.transitioning = false }.bind(this) }).setStyles({'opacity': 0, 'left': 0}).fade('in');
this.tempContainer.set('tween', { 'duration': this.options.fadeDuration, 'transition': this.options.fadeTransition }).fade('out');
},
levelUp: function() {
if(this.view == 'decade' || this.transitioning) return;
this.switchContainers();
//Set viewdates and render
switch(this.view) {
case 'month': this.renderYear(); break;
case 'year': this.renderDecade(); break;
}
//Tween the new view in and old view out
this.transitioning = true;
this.currentContainer.set('tween', { 'duration': this.options.fadeDuration, 'transition': this.options.fadeTransition,
'onComplete': function() { this.transitioning = false }.bind(this) }).setStyles({'opacity': 0, 'left': 0}).fade('in');
this.tempContainer.set('tween', { 'duration': this.options.fadeDuration, 'transition': this.options.fadeTransition }).fade('out');
},
switchContainers: function() {
this.currentContainer = this.currentContainer.hasClass('a') ? this.element.getElement('.container.b') : this.element.getElement('.container.a');
this.tempContainer = this.tempContainer.hasClass('a') ? this.element.getElement('.container.b') : this.element.getElement('.container.a');
this.currentContainer.empty().removeClass('month').removeClass('year-decade').setStyles({ 'opacity': 1, 'display': 'block', 'z-index': 999 });
this.tempContainer.setStyle('z-index', 998);
this.label.addClass('clickable');
this.arrowLeft.setStyle('visibility', 'visible');
this.arrowRight.setStyle('visibility', 'visible');
},
pick: function(e) {
if($defined(e)) {
this.selectedDate = e.target.date;
this.element.getElements('.selected').removeClass('selected');
e.target.addClass('selected');
}
var value = this.format(this.selectedDate);
if(!this.options.injectInsideTarget) {
switch(this.target.get('tag')) {
case 'input': this.target.set('value', value); break;
default: this.target.set('html', value);
}
(this.hide.bind(this)).delay(150);
}
if($defined(this.hiddenInput)) this.hiddenInput.set('value', this.format(this.selectedDate, this.options.hiddenInputFormat));
this.options.pickFunction(this.selectedDate);
},
position: function() {
var top, left;
var coordinates = this.target.getCoordinates();
switch(this.options.alignX) {
case 'left':
left = coordinates.left;
break;
case 'middle':
left = coordinates.left + (coordinates.width / 2) - (this.element.getWidth() / 2);
break;
case 'right': default:
left = coordinates.left + coordinates.width;
}
switch(this.options.alignY) {
case 'bottom':
top = coordinates.top + coordinates.height;
break;
case 'top':
top = coordinates.top - this.element.getHeight();
break;
case 'ceiling': default:
top = coordinates.top;
}
left += this.options.offsetX.toInt();
top += this.options.offsetY.toInt();
this.element.setStyles({ 'top': top, 'left': left });
},
show: function() {
if(!this.visible & !this.options.alwaysShow) {
this.visible = true;
if(!Browser.Engine.trident) {
this.element.setStyles({ 'opacity': 0, 'display': 'block' });
if(!this.options.injectInsideTarget) this.position();
this.element.set('tween', { 'duration': this.options.toggleDuration, 'transition': this.options.fadeTransition }).fade('in');
} else {
this.element.setStyles({ 'opacity': 1, 'display': 'block' });
if(!this.options.injectInsideTarget) this.position();
}
}
},
hide: function() {
if(this.visible & !this.options.alwaysShow) {
this.visible = false;
if(!Browser.Engine.trident) {
this.element.set('tween', { 'duration': this.options.toggleDuration, 'transition': this.options.fadeTransition,
'onComplete': function() { this.element.setStyle('display', 'none') }.bind(this) }).fade('out');
} else this.element.setStyle('display', 'none');
}
},
toggle: function() {
if(this.visible) this.hide();
else this.show();
},
format: function(date, format) {
if(!$defined(format)) format = this.options.format;
if(!$defined(date)) return;
format = format.replace(/%([a-z%])/gi,
function($1, $2) {
switch($2) {
case 'D': return date.get('date');
case 'n': return date.get('mo') + 1;
case 't': return (date.getTime() / 1000).toInt();
}
return '%'+ $2;
}
);
return date.format(format);
},
outsideClick: function(e) {
if(this.visible) {
var elementCoords = this.element.getCoordinates();
var targetCoords = this.target.getCoordinates();
if(((e.page.x < elementCoords.left || e.page.x > (elementCoords.left + elementCoords.width)) ||
(e.page.y < elementCoords.top || e.page.y > (elementCoords.top + elementCoords.height))) &&
((e.page.x < targetCoords.left || e.page.x > (targetCoords.left + targetCoords.width)) ||
(e.page.y < targetCoords.top || e.page.y > (targetCoords.top + targetCoords.height))) ) this.hide();
}
},
//Version 1.0.1 addition, can easily be called from outside
setDate: function(value, pick) {
if(!$defined(pick)) pick = true;
if($type(value) == 'date') {
var date = value.clearTime();
} else {
var date = $chk(value) ? new Date().parse(this.target.get('value')).clearTime() : new Date().clearTime();
}
if(date.isValid()) {
this.selectedDate = date.clone();
this.viewDate = this.selectedDate.clone().set('date', 1);
this.render();
if(pick) this.pick();
}
}
});
Style.css is
.calendar-eightysix .body {
position: relative;
}
.calendar-eightysix .body .inner .container {
position: absolute;
left: 0;
}
In jquery replace the switchContainers: function() with
switchContainers: function() {
this.currentContainer = this.currentContainer.hasClass('a') ? this.element.getElement('.container.b') : this.element.getElement('.container.a');
this.tempContainer = this.tempContainer.hasClass('a') ? this.element.getElement('.container.b') : this.element.getElement('.container.a');
this.currentContainer.empty().removeClass('month').removeClass('year-decade').setStyles({ 'opacity': 1, 'display': 'block', 'z-index': 999 });
this.tempContainer.setStyles({ 'display': 'none', 'z-index': 998 });
this.currentContainer.hasClass('a') ? this.currentContainer.setStyles({ 'opacity': 1, 'display': 'block', 'z-index': 999 }) : '';
this.label.addClass('clickable');
this.arrowLeft.setStyle('visibility', 'visible');
this.arrowRight.setStyle('visibility', 'visible');
},
In style.css
Replace the .calendar-eightysix .body .inner .container with
.calendar-eightysix .body .inner .container {
left: 0;
}
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'm using this chat http://tutorialzine.com/2010/10/ajax-web-chat-php-mysql/ and I tried to turn on the bbcodes but: http://imageshack.us/photo/my-images/827/bbcodes1.png/
I tried to replace in
scripts.js
text : text.replace(/</g,'<').replace(/>/g,'>')
with
text : text.replace(/</g,'<').
replace(/>/g,'>').
replace(/\[b\]((\s|.)+?)\[\/b\]/,'<b>\\1</b>')
This is my bbcode function, you can edit the codes variable to support more bbcode. For now, it support only [b], [i], [u], [url], [img].
[read] is my special bbcode for my website
function bbcode(text){
var codes = {};
codes['url'] = {
params : {
href : ''
},
html: "$text"
};
codes['b'] = {
params : {
},
html : "<b>$text</b>"
};
codes['i'] = {
params : {
},
html : "<i>$text</i>"
};
codes['u'] = {
params : {
},
html : "<u>$text</u>"
};
codes['img'] = {
params : {
},
html : "<img src=\"$text\" />"
};
codes['read'] = {
params : {
},
text : function(text){
for(var x in codes){
text = text.replace(new RegExp('\\[' + x + '\\]','gi'), '').replace(new RegExp('\\[\\/' + x + '\\]','gi'), '');
}
return encodeURIComponent(text);
},
process: function(text){
return text;
},
html : "$text <object type=\"application/x-shockwave-flash\" data=\"" + GLOBALS.baseUrl + "/player_mp3_maxi.swf\" width=\"200\" height=\"20\"><param name=\"movie\" value=\"" + GLOBALS.baseUrl + "/player_mp3_maxi.swf\" /><param name=\"bgcolor\" value=\"#ffffff\" /><param name=\"FlashVars\" value=\"mp3=http://api.ispeech.org/api/rest?apikey%3Ddeveloperdemokeydeveloperdemokey%26action%3Dconvert%26voice%3Dusenglishfemale1%26text%3D$TEXT&width=200&showslider=1\" /></object>"
};
text = text.replace(/\</g, '<').replace(/\>/g, '>');
var nomore = false;
while(!nomore){
var matches = text.match(/\[([^\]]+)\]/gi);
if(matches == null)
return text;
nomore = true;
for(var i = 0; i < matches.length; i++){
var code = matches[i].substring(1, matches[i].length - 1);
var parts = code.split(/\s+/);
if(typeof codes[parts[0]] == 'object'){
//is exist
var obj = {};
//get the params
for(var j = 1; j < parts.length; j++)
{
var temp = parts[j].split('=');
if(typeof codes[parts[0]].params[temp[0]] != 'undefined'){
obj[temp[0]] = (temp.length > 1) ? (temp[1].indexOf('"') == 0 ? temp[1].substring(1, temp[1].length - 1) : temp[1]) : '';
}
}
//find the text
var index = text.indexOf(matches[i]);
var index2 = text.indexOf('[/'+parts[0]+']', index);
if(index2 == -1)
index2 = text.length;
var t = text.substring(index + matches[i].length, index2);
if(typeof codes[parts[0]].process == 'function'){
t = codes[parts[0]].process(t);
}if(typeof codes[parts[0]].text == 'function'){
t2 = codes[parts[0]].text(t);
}
var html = codes[parts[0]].html;
for(var x in obj)
html = html.replace("$" + x, obj[x]);
html = html.replace(/\$text/g, t);
if(typeof codes[parts[0]].text == 'function'){
html = html.replace(/\$TEXT/g, t2);
}
text = text.substr(0, index) + html + text.substr(index2 + parts[0].length + 3);
nomore = false;
}
}
}
text = text.replace(/\n/g, "<br />");
return text;
}
You can use this by:
text: bbcode(text)