Related
I've got a Laravel project but I think I have an idea of how to incorporate the Dynamic Web Twain (https://www.dynamsoft.com/Products/WebTWAIN_Overview.aspx) into it.
The only problem is I'm not quite sure how I would go about adding additional fields to the scanner UI (like what you see here: https://demo.dynamsoft.com/dwt/online_demo_scan.aspx).
At the moment my Laravel site has a working upload portion to a model where I can submit attachments, however, with the attachment form are fields that include "visibility", "type", "upload location" etc. etc. But I can't seem to figure out how I would add fields like what I already use.
From what I've tested, this is an incredibly useful tool and would work well if I could integrate it into all aspects of my site.
The closest thing I can find is here: https://developer.dynamsoft.com/dwt/api-reference/uploading-downloading/sethttpformfield
Which references what is done in this demo: https://demo.dynamsoft.com/Samples/dwt/Scan-Documents-and-Upload-Them/DWT_Scan_Upload_Demo.html
As you can see, you can add a field name and field value, using the "+" button, but I want to add some fields in the form that are available immediately. The other issue that I might need to work around is if I use this demo and add a value and name, this is how everything is posted and I'm not sure how to translate to something my project can understand.
-----------------------------23491353817351
Content-Disposition: form-data; name="This is a field"
Wow
-----------------------------23491353817351
Content-Disposition: form-data; name="RemoteFile"; filename="507-0.jpg"
Content-Type: application/octet-stream
ÿØÿà
This aspect is a necessary part of my project, so unfortunately there's no real way around this besides moving forward.
This is the current script in the online demo:
Dynamsoft.WebTwainEnv.RegisterEvent('OnWebTwainReady', Dynamsoft_OnReady); // Register OnWebTwainReady event. This event fires as soon as Dynamic Web TWAIN is initialized and ready to be used
var DWObject, blankField = "", extrFieldsCount = 0, upload_returnSth = true;
var CurrentPathName = unescape(location.pathname);
var CurrentPath = CurrentPathName.substring(0, CurrentPathName.lastIndexOf("/") + 1);
var strHTTPServer = location.hostname;
var strActionPage;
var scriptLanguages = [
{ desc: "PHP", val: "php" },
{ desc: "PHP-MySQL", val: "phpMySQL" },
{ desc: "CSharp", val: "csharp" },
{ desc: "CSharp-MSSQL", val: "csMSSQL" },
{ desc: "VB.NET", val: "vbnet" },
{ desc: "VBNET-MSSQL", val: "vbnetMSSQL" },
{ desc: "JSP", val: "jsp" },
{ desc: "JSP-Oracle", val: "jspOracle" },
{ desc: "ASP", val: "asp" },
{ desc: "ASP-MSSQL", val: "aspMSSQL" },
{ desc: "ColdFusion", val: "cfm" },
{ desc: "CS-Azure", val: "csAzure" }
];
function languageSelected() {
if (document.getElementById("ddlLanguages").selectedIndex > 7)
upload_returnSth = false;
else
upload_returnSth = true;
if ([0, 2, 4, 6].indexOf(document.getElementById("ddlLanguages").selectedIndex) == -1) {
document.getElementById("extra-fields-div-id").style.display = 'none';
document.getElementById('div-extra-fields').style.display = 'none';
}
else {
document.getElementById("extra-fields-div-id").style.display = '';
if (document.getElementById('div-extra-fields').children.length > 1 ||
document.getElementById('div-extra-fields').children[0].children[0].value != '') {
document.getElementById('div-extra-fields').style.display = '';
}
}
}
function addAField() {
extrFieldsCount++;
if (extrFieldsCount == 3) {
document.getElementById('div-extra-fields').style.overflowY = 'scroll';
}
if (document.getElementById('div-extra-fields').style.display == "none")
document.getElementById('div-extra-fields').style.display = '';
else {
document.getElementById('div-extra-fields').appendChild(blankField);
blankField = document.getElementsByClassName('div-fields-item')[extrFieldsCount - 1].cloneNode(true);
}
}
function downloadPDFR() {
DCP_DWT_OnClickCloseInstall();
DWObject.Addon.PDF.Download(
CurrentPath + '/Resources/addon/Pdf.zip',
function () {/*console.log('PDF dll is installed');*/
},
function (errorCode, errorString) {
console.log(errorString);
}
);
}
function Dynamsoft_OnReady() {
blankField = document.getElementsByClassName('div-fields-item')[0].cloneNode(true);
DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); // Get the Dynamic Web TWAIN object that is embeded in the div with id 'dwtcontrolContainer'
if (DWObject) {
DWObject.Width = 505;
DWObject.Height = 600;
for (var i = 0; i < scriptLanguages.length; i++)
document.getElementById("ddlLanguages").options.add(new Option(scriptLanguages[i].desc, i));
document.getElementById("ddlLanguages").options.selectedIndex = 2;
/*
* Make sure the PDF Rasterizer and OCR add-on are already installedsample
*/
if (!Dynamsoft.Lib.env.bMac) {
var localPDFRVersion = '';
if(Dynamsoft.Lib.product.bChromeEdition){
localPDFRVersion = DWObject._innerFun('GetAddOnVersion', '["pdf"]');
}
else {
localPDFRVersion = DWObject.getSWebTwain().GetAddonVersion("pdf");
}
if (localPDFRVersion != Dynamsoft.PdfVersion) {
var ObjString = [];
ObjString.push('<div class="p15" id="pdfr-install-dlg">');
ObjString.push('The <strong>PDF Rasterizer</strong> is not installed on this PC<br />Please click the button below to get it installed');
ObjString.push('<p class="tc mt15 mb15"><input type="button" value="Install PDF Rasterizer" onclick="downloadPDFR();" class="btn lgBtn bgBlue" /><hr></p>');
ObjString.push('<i><strong>The installation is a one-time process</strong> <br />It might take some time depending on your network.</i>');
ObjString.push('</div>');
Dynamsoft.WebTwainEnv.ShowDialog(400, 310, ObjString.join(''));
}
else {
/**/
}
}
}
}
function AcquireImage() {
if (DWObject) {
var bSelected = DWObject.SelectSource();
if (bSelected) {
var OnAcquireImageSuccess, OnAcquireImageFailure;
OnAcquireImageSuccess = OnAcquireImageFailure = function () {
DWObject.CloseSource();
};
DWObject.OpenSource();
DWObject.IfDisableSourceAfterAcquire = true; //Scanner source will be disabled/closed automatically after the scan.
DWObject.AcquireImage(OnAcquireImageSuccess, OnAcquireImageFailure);
}
}
}
function LoadImages() {
if (DWObject) {
DWObject.Addon.PDF.SetResolution(300);
DWObject.Addon.PDF.SetConvertMode(EnumDWT_ConverMode.CM_RENDERALL);
DWObject.LoadImageEx('', 5,
function () {
},
function (errorCode, errorString) {
alert('Load Image:' + errorString);
}
);
}
}
function OnHttpUploadSuccess() {
console.log('successful');
}
function OnHttpServerReturnedSomething(errorCode, errorString, sHttpResponse) {
//console.log(errorString);
var textFromServer = sHttpResponse;
_printUploadedFiles(textFromServer);
}
function _printUploadedFiles(info) {
//console.log(info);
if (info.indexOf('DWTUploadFileName') != -1) {
var url, _strPort;
DWObject.IfSSL = Dynamsoft.Lib.detect.ssl;
_strPort = location.port == "" ? 80 : location.port
url = 'http://' + location.hostname + ':' + location.port
if (Dynamsoft.Lib.detect.ssl == true) {
_strPort = location.port == "" ? 443 : location.port;
url = 'https://' + location.hostname + ':' + location.port
}
var savedIntoToDB = false, imgIndexInDB = "-1";
if (info.indexOf("DWTUploadFileIndex:") != -1) {
savedIntoToDB = true;
imgIndexInDB = info.substring(info.indexOf('DWTUploadFileIndex') + 19, info.indexOf('DWTUploadFileName'));
//console.log(imgIndexInDB);
}
var fileName = info.substring(info.indexOf('DWTUploadFileName') + 18, info.indexOf('UploadedFileSize'));
var fileSize = info.substr(info.indexOf('UploadedFileSize') + 17);
if (savedIntoToDB) {
if (info.indexOf('CSHARP') != -1) {
url += CurrentPath + 'action/csharp-db.aspx?imgID=' + imgIndexInDB;
}
else if (info.indexOf('VBNET') != -1) {
url += CurrentPath + 'action/vbnet-db.aspx?imgID=' + imgIndexInDB;
}
else if (info.indexOf('PHP') != -1) {
url += CurrentPath + 'action/php-mysql.php?imgID=' + imgIndexInDB;
}
else if (info.indexOf('JSP') != -1) {
url += CurrentPath + 'action/jsp-oracle.jsp?imgID=' + imgIndexInDB;
}
}
else {
url += CurrentPath + 'action/UploadedImages/' + encodeURI(fileName);
}
var newTR = document.createElement('tr');
_str = "<td class='tc'><a class='bluelink'" + ' href="' + url + '" target="_blank">' + fileName + "</a></td>"
+ "<td class='tc'>" + fileSize + '</td>';
if (info.indexOf("FieldsTrue:") != -1)
_str += "<td class='tc'><a class='bluelink'" + '" href="' + url.substring(0, url.length - 4) + '_1.txt' + '" target="_blank">Fields</td>';
else {
_str += "<td class='tc'>No Fields</td>";
}
newTR.innerHTML = _str;
document.getElementById('div-uploadedFile').appendChild(newTR);
}
}
function upload_preparation(_name) {
DWObject.IfShowCancelDialogWhenImageTransfer = !document.getElementById('quietScan').checked;
strActionPage = CurrentPath + 'action/';
switch (document.getElementById("ddlLanguages").options.selectedIndex) {
case 0: strActionPage += "php.php"; break;
case 2: strActionPage += "csharp.aspx"; break;
case 6: strActionPage += "jsp.jsp"; break;
case 4: strActionPage += "vbnet.aspx"; break;
case 8: strActionPage += "asp.asp"; break;
case 10: strActionPage += "cfm.cfm"; break;
case 1: strActionPage += "php-mysql.php?imgID=new"; break;
case 7: strActionPage += "jsp-oracle.jsp?imgID=new"; break;
case 3: strActionPage += "csharp-db.aspx?imgID=new"; break;
case 5: strActionPage += "vbnet-db.aspx?imgID=new"; break;
case 9: strActionPage += "asp-db.asp"; break;
case 11: preparetoUploadtoAzure(_name); break;
default: break;
}
DWObject.IfSSL = Dynamsoft.Lib.detect.ssl;
var _strPort = location.port == "" ? 80 : location.port;
if (Dynamsoft.Lib.detect.ssl == true)
_strPort = location.port == "" ? 443 : location.port;
DWObject.HTTPPort = _strPort;
if ([0, 2, 4, 6].indexOf(document.getElementById("ddlLanguages").selectedIndex) != -1) {
/* Add Fields to the Post */
var fields = document.getElementsByClassName('div-fields-item');
DWObject.ClearAllHTTPFormField();
for (var n = 0; n < fields.length; n++) {
var o = fields[n];
if (o.children[0].value != '')
DWObject.SetHTTPFormField(o.children[0].value, o.children[1].value);
}
}
}
function UploadImage_inner() {
if (DWObject.HowManyImagesInBuffer == 0)
return;
var Digital = new Date();
var uploadfilename = Digital.getMilliseconds(); // Uses milliseconds according to local time as the file name
upload_preparation(uploadfilename);
// Upload the image(s) to the server asynchronously
if (document.getElementById("ddlLanguages").options.selectedIndex == 11 /*Azure*/) return;
if (document.getElementsByName('ImageType')[0].checked) {
var uploadIndexes = [];
for (var i = DWObject.HowManyImagesInBuffer - 1; i > -1 ; i--) {
uploadIndexes.push(i);
}
var uploadJPGsOneByOne = function (errorCode, errorString, sHttpResponse) {
if (upload_returnSth)
_printUploadedFiles(sHttpResponse);
if (uploadIndexes.length > 0) {
var _index = uploadIndexes.pop();
if (upload_returnSth)
DWObject.HTTPUploadThroughPost(strHTTPServer, _index, strActionPage, uploadfilename + "-" + _index.toString() + ".jpg", OnHttpUploadSuccess, uploadJPGsOneByOne);
else
DWObject.HTTPUploadThroughPost(strHTTPServer, _index, strActionPage, uploadfilename + "-" + _index.toString() + ".jpg", uploadJPGsOneByOne, OnHttpServerReturnedSomething);
}
}
var _index = uploadIndexes.pop();
if (upload_returnSth)
DWObject.HTTPUploadThroughPost(strHTTPServer, _index, strActionPage, uploadfilename + "-" + _index.toString() + ".jpg", OnHttpUploadSuccess, uploadJPGsOneByOne);
else
DWObject.HTTPUploadThroughPost(strHTTPServer, _index, strActionPage, uploadfilename + "-" + _index.toString() + ".jpg", uploadJPGsOneByOne, OnHttpServerReturnedSomething);
}
else if (document.getElementsByName('ImageType')[1].checked) {
DWObject.HTTPUploadAllThroughPostAsMultiPageTIFF(strHTTPServer, strActionPage, uploadfilename + ".tif", OnHttpUploadSuccess, OnHttpServerReturnedSomething);
}
else if (document.getElementsByName('ImageType')[2].checked) {
DWObject.HTTPUploadAllThroughPostAsPDF(strHTTPServer, strActionPage, uploadfilename + ".pdf", OnHttpUploadSuccess, OnHttpServerReturnedSomething);
}
}
function UploadImage() {
if (DWObject) {
var nCount = 0, nCountUpLoaded = 0, aryFilePaths = [];
if (document.getElementById('uploadDirectly').checked) {
DWObject.IfShowCancelDialogWhenImageTransfer = false;
function ds_load_file_to_upload_directly(bSave, filesCount, index, path, filename) {
nCount = filesCount;
var filePath = path + "\\" + filename;
aryFilePaths.push(filePath);
if (aryFilePaths.length == nCount) {
upload_preparation();
var i = 0;
function uploadFileOneByOne() {
DWObject.HTTPUploadThroughPostDirectly(strHTTPServer, filePath, strActionPage, filename,
function () {
console.log('Upload Image:' + aryFilePaths[i] + ' -- successful');
i++;
if (i != nCount)
uploadFileOneByOne();
else
DWObject.UnregisterEvent('OnGetFilePath', ds_load_file_to_upload_directly);
},
OnHttpServerReturnedSomething
);
}
uploadFileOneByOne();
}
}
DWObject.RegisterEvent('OnGetFilePath', ds_load_file_to_upload_directly);
DWObject.ShowFileDialog(false, "Any File | *.*", 0, "", "", true, true, 0);
}
else {
UploadImage_inner();
}
}
}
/*******************/
/* Upload to Azure */
var Base64Binary = {
_keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
decode: function (input, arrayBuffer) {
//get last chars to see if are valid
var lkey1 = this._keyStr.indexOf(input.charAt(input.length - 1));
var lkey2 = this._keyStr.indexOf(input.charAt(input.length - 2));
var bytes = (input.length / 4) * 3;
if (lkey1 == 64) bytes--; //padding chars, so skip
if (lkey2 == 64) bytes--; //padding chars, so skip
var uarray;
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
var j = 0;
if (arrayBuffer)
uarray = new Uint8Array(arrayBuffer);
else
uarray = new Uint8Array(bytes);
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
for (i = 0; i < bytes; i += 3) {
//get the 3 octects in 4 ascii chars
enc1 = this._keyStr.indexOf(input.charAt(j++));
enc2 = this._keyStr.indexOf(input.charAt(j++));
enc3 = this._keyStr.indexOf(input.charAt(j++));
enc4 = this._keyStr.indexOf(input.charAt(j++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
uarray[i] = chr1;
if (enc3 != 64) uarray[i + 1] = chr2;
if (enc4 != 64) uarray[i + 2] = chr3;
}
return uarray;
}
}
function uploadImageInner_azure(blobSasUrl, fileDataAsArrayBuffer) {
var ajaxRequest = new XMLHttpRequest();
try {
ajaxRequest.open('PUT', blobSasUrl, true);
ajaxRequest.setRequestHeader('x-ms-blob-type', 'BlockBlob');
ajaxRequest.send(fileDataAsArrayBuffer);
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4) {
console.log('Upload image to azure server successfully.');
}
}
}
catch (e) {
console.log("can't upload the image to server.\n" + e.toString());
}
}
function preparetoUploadtoAzure(__name) {
var uploadfilename = '';
//For JPEG, upload the current image
if (document.getElementsByName('ImageType')[0].checked) {
DWObject.SelectedImagesCount = 1;
DWObject.SetSelectedImageIndex(0, DWObject.CurrentImageIndexInBuffer);
DWObject.GetSelectedImagesSize(EnumDWT_ImageType.IT_JPG);
uploadfilename = __name + '.jpg';
}
else { //For TIFF, PDF, upload all images
var count = DWObject.HowManyImagesInBuffer;
DWObject.SelectedImagesCount = count;
for (var i = 0; i < count; i++) {
DWObject.SetSelectedImageIndex(i, i);
}
if (document.getElementsByName('ImageType')[1].checked) {
DWObject.GetSelectedImagesSize(EnumDWT_ImageType.IT_TIF);
uploadfilename = __name + '.tif';
}
else {
DWObject.GetSelectedImagesSize(EnumDWT_ImageType.IT_PDF);
uploadfilename = __name + '.pdf';
}
}
var strImg, aryImg, _uint8_STR, _bin_ARR, _blobImg;
strImg = DWObject.SaveSelectedImagesToBase64Binary();
// convert base64 to Uint8Array
var bytes = (strImg.length / 4) * 3;
var _temp = new ArrayBuffer(bytes);
_uint8_STR = Base64Binary.decode(strImg, _temp);
// convert Uint8Array to blob
_blobImg = new Blob([_uint8_STR]);
// upload to Azure server
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
uploadImageInner_azure(xhr.responseText, _blobImg);
}
}
var actionPageFullPath = CurrentPath + 'action/' + 'azure.aspx?imageName=' + uploadfilename;
xhr.open('GET', actionPageFullPath, true);
xhr.send();
}
/*******************/
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 new to Javascript, I got this Javascript timer from the net. I'm trying to stop the timer and insert the stopped time into the database if a certain PHP variable is set, but I'm not sure how to stop the timer. Here's the code. I saw this post and sadly, I still can't get it to work. How to stop a timer function from running?
Thanks!
<script type="text/javascript">
/**********************************************************************************************
* CountUp script by Praveen Lobo (http://PraveenLobo.com/techblog/javascript-countup-timer/)
* This notice MUST stay intact(in both JS file and SCRIPT tag) for legal use.
* http://praveenlobo.com/blog/disclaimer/
**********************************************************************************************/
function CountUp(initDate, id){
this.beginDate = new Date(initDate);
this.countainer = document.getElementById(id);
this.numOfDays = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
this.borrowed = 0, this.years = 0, this.months = 0, this.days = 0;
this.hours = 0, this.minutes = 0, this.seconds = 0;
this.updateNumOfDays();
this.updateCounter();
}
CountUp.prototype.updateNumOfDays=function(){
var dateNow = new Date();
var currYear = dateNow.getFullYear();
if ( (currYear % 4 == 0 && currYear % 100 != 0 ) || currYear % 400 == 0 ) {
this.numOfDays[1] = 29;
}
var self = this;
setTimeout(function(){self.updateNumOfDays();}, (new Date((currYear+1), 1, 2) - dateNow));
}
CountUp.prototype.datePartDiff=function(then, now, MAX){
var diff = now - then - this.borrowed;
this.borrowed = 0;
if ( diff > -1 ) return diff;
this.borrowed = 1;
return (MAX + diff);
}
CountUp.prototype.calculate=function(){
var currDate = new Date();
var prevDate = this.beginDate;
this.seconds = this.datePartDiff(prevDate.getSeconds(), currDate.getSeconds(), 60);
this.minutes = this.datePartDiff(prevDate.getMinutes(), currDate.getMinutes(), 60);
this.hours = this.datePartDiff(prevDate.getHours(), currDate.getHours(), 24);
this.days = this.datePartDiff(prevDate.getDate(), currDate.getDate(), this.numOfDays[currDate.getMonth()]);
this.months = this.datePartDiff(prevDate.getMonth(), currDate.getMonth(), 12);
this.years = this.datePartDiff(prevDate.getFullYear(), currDate.getFullYear(),0);
}
CountUp.prototype.addLeadingZero=function(value){
return value < 10 ? ("0" + value) : value;
}
CountUp.prototype.formatTime=function(){
this.seconds = this.addLeadingZero(this.seconds);
this.minutes = this.addLeadingZero(this.minutes);
this.hours = this.addLeadingZero(this.hours);
}
CountUp.prototype.updateCounter=function(){
this.calculate();
this.formatTime();
this.countainer.innerHTML =
" <strong>" + this.hours + "</strong> <small>" + (this.hours == 1? ":" : ":") + "</small>" +
" <strong>" + this.minutes + "</strong> <small>" + (this.minutes == 1? ":" : ":") + "</small>" +
" <strong>" + this.seconds + "</strong> <small>" + "</small>";
var self = this;
setTimeout(function(){self.updateCounter();}, 1000);
}
<?php if(isset($results['calltime'])) {$timevar= date("M d, Y H:i:s",strtotime($results['calltime']));}?>
window.onload=function(){ new CountUp('<?php echo $timevar; ?>', 'counter'); }
//I need a function to stop timer if (isset($results['firstcall_time']))
</script>
In your method updateCounter() You have following statement
setTimeout(function(){self.updateCounter();}, 1000);
make it like following first.
myTimer = setTimeout(function(){self.updateCounter();}, 1000);
and then whenever you want to stop the timer call this method.
clearTimeout(myTimer);
and then record the time.
It uses setTimeout for counting so you have to use clearTimeout for stopping the contdown.
reffer Clear Timeout
Cheers
In the lines:
setTimeout(function(){self.updateNumOfDays();}, (new Date((currYear+1), 1, 2) - dateNow));
And
setTimeout(function(){self.updateCounter();}, 1000);
You can see the recursion is being used, thus the timer keeps running.
So when you want to stop the timer do SOMETHING like this:
var flag = true;
<?php if (isset($results['firstcall_time'])){ ?>
flag = false;
<?php } ?>
And modify your script a little bit as:
setTimeout(function(){if(flag){self.updateNumOfDays();}else{//write code to cleartimeout}}, (new Date((currYear+1), 1, 2) - dateNow));//check for the flag before recursion
And
setTimeout(function(){if(flag){self.updateCounter();}}else{//write code to cleartimeout}, 1000);
He isn't using a timer. He is using setTimeout, but the executing function, is the same method, sort-of like recursion (but strictly speaking, it isn't). So, it's on going. Hope this makes sense.
A timer is implemented like:
// Start
var timerId = setInterval(func() {
// your code to execute
}, 5000);
// Stop
clearInterval(timerId);
I've added a stop method to CountUp. So you should now be able to do this:
// Start
var counter = new CountUp(new Date(), 'div');
// Stop
counter.stop();
Here's the code. I've just hand coded in here, so if there are any typos or something doesn't work then post a comment.
function CountUp(initDate, id){
this.beginDate = new Date(initDate);
this.countainer = document.getElementById(id);
this.numOfDays = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
this.borrowed = 0, this.years = 0, this.months = 0, this.days = 0;
this.hours = 0, this.minutes = 0, this.seconds = 0;
this.daysTimerId = setInterval(this.updateNumOfDays(), this.getDaysTimerInterval());
this.updateTimerId = setInterval(this.updateCounter(), 1000);
}
CountUp.prototype.stop=function(){
clearInterval(this.daysTimerId);
clearInterval(this.updateTimerId);
}
CountUp.prototype.getDaysTimerInterval=function(dt){
var dateNow = dt || new Date();
return (new Date((dateNow.getFullYear()+1), 1, 2) - dateNow));
}
CountUp.prototype.updateNumOfDays=function(){
var dateNow = new Date();
var currYear = dateNow.getFullYear();
if ( (currYear % 4 == 0 && currYear % 100 != 0 ) || currYear % 400 == 0 ) {
this.numOfDays[1] = 29;
}
// var self = this;
// setTimeout(function(){self.updateNumOfDays();}, self.getDaysTimerInterval(dateNow));
}
CountUp.prototype.datePartDiff=function(then, now, MAX){
var diff = now - then - this.borrowed;
this.borrowed = 0;
if ( diff > -1 ) return diff;
this.borrowed = 1;
return (MAX + diff);
}
CountUp.prototype.calculate=function(){
var currDate = new Date();
var prevDate = this.beginDate;
this.seconds = this.datePartDiff(prevDate.getSeconds(), currDate.getSeconds(), 60);
this.minutes = this.datePartDiff(prevDate.getMinutes(), currDate.getMinutes(), 60);
this.hours = this.datePartDiff(prevDate.getHours(), currDate.getHours(), 24);
this.days = this.datePartDiff(prevDate.getDate(), currDate.getDate(), this.numOfDays[currDate.getMonth()]);
this.months = this.datePartDiff(prevDate.getMonth(), currDate.getMonth(), 12);
this.years = this.datePartDiff(prevDate.getFullYear(), currDate.getFullYear(),0);
}
CountUp.prototype.addLeadingZero=function(value){
return value < 10 ? ("0" + value) : value;
}
CountUp.prototype.formatTime=function(){
this.seconds = this.addLeadingZero(this.seconds);
this.minutes = this.addLeadingZero(this.minutes);
this.hours = this.addLeadingZero(this.hours);
}
CountUp.prototype.updateCounter=function(){
this.calculate();
this.formatTime();
this.countainer.innerHTML =
" <strong>" + this.hours + "</strong> <small>" + (this.hours == 1? ":" : ":") + "</small>" +
" <strong>" + this.minutes + "</strong> <small>" + (this.minutes == 1? ":" : ":") + "</small>" +
" <strong>" + this.seconds + "</strong> <small>" + "</small>";
// var self = this;
// setTimeout(function(){self.updateCounter();}, 1000);
}
Here is how I stopped the counter:
I inserted this few lines before "CountUp.prototype.updateCounter=function(){"
var today=new Date();
var start=new Date(2013,10,25,5,35,0); //example: Stop date
diff = start-today;
Then, inside updateCounter function, instead of directly call the setTimeout I added a condition:
if ( ( (this.seconds==0) && (this.minutes==0) (this.hours==0) && (this.days==0) ) || (diff <=0) ) { //on the fly (page is laready open with the counter running) or onload
//Time's up!
} else {
setTimeout(function(){self.updateCounter();}, 1000);
}
So the new code will look like this:
var today=new Date();
var start=new Date(2013,10,25,5,35,0);
diff = start-today;
Counter.prototype.updateCounter=function(){
this.calculate();
this.formatTime();
this.countainer.innerHTML = " <strong>" + this.seconds + "</strong> " + (this.seconds == 1? ":" : ":")+
" <strong>" + this.minutes + "</strong> " + (this.minutes == 1? ":" : ":")+
" <strong>" + this.hours + "</strong> " + (this.hours == 1? ":" : ":")+
" <strong>" + this.days + "</strong> " + (this.days == 1? ":" : "");
var self = this;
if ( ( (this.seconds==0) && (this.minutes==0) (this.hours==0) && (this.days==0) ) || (diff <=0) ) { //on the fly or onload
//Time's up!
} else {
setTimeout(function(){self.updateCounter();}, 1000);
}
}
Hope that will help.
Shams
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 currently have a table that is being populated by a MySQL table, in turn i want to take the data from these cells and use them to create a simulated real time update, i have it working however due to having multiple rows im using for loops in the javascript functions and i believe this is causing the other functions not to run and i cannot figure out a way round it.
Javascript Code:
var seconds = 5;
var divid = "status";
var url = "boo.php";
var timeout;
function refreshdiv(){
// The XMLHttpRequest object
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
}
catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
alert("Your browser does not support AJAX.");
return false;
}
}
}
// Timestamp for preventing IE caching the GET request
fetch_unix_timestamp = function()
{
return parseInt(new Date().getTime().toString().substring(0, 10))
}
var timestamp = fetch_unix_timestamp();
var nocacheurl = url+"?t="+timestamp;
// The code...
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
document.getElementById(divid).innerHTML=xmlHttp.responseText;
setTimeout('refreshdiv()',seconds*1000);
}
}
xmlHttp.open("GET",nocacheurl,true);
xmlHttp.send(null);
}
// Start the refreshing process
var seconds;
window.onload = function startrefresh(){
setTimeout('refreshdiv()',seconds*1000);
}
function runningtime(int) {
if(int == 0) { //if there is data
console.log("int=0 so no data is present, int: " + int);
} else if(int == 1){
var isRunning = new Array();
isRunning[0] = " ";
for (var i=0; i < 3; i++) {
var bool = 'running' + i;
console.log("Running = " + bool);
running = document.getElementById(bool).innerHTML.substring(10,11);
console.log("running: " + running);
if(isRunning[i] == "1") {
var time = 'Time' + i;
a= document.getElementById(time).innerHTML;
console.log("a= " + a);
hour=a.substring(0,2);
min= a.substring(3,5);
sec= a.substring(6,8);
sec==sec++;
if (min<=9) { min="0"+min; }
if (sec<=9) { sec="0"+sec; }
time = (hour + ":" + min + ":" + sec + " ");
if (document.getElementById) { document.getElementById(time).innerHTML = time; }
else if (document.layers) {
document.layers.theTime.document.write(time);
document.layers.theTime.document.close(); }
} else {
//Do nothing
return;
}
}
timeout = setTimeout("runningtime(1)", 1000);
}
}
function experiencehour(exp) {
if(exp == 0) { //if there is dexphourtexphour
console.log("exp=0 so no data is present, exp: " + exp);
} else if(exp == 1){
var isRunning = new Array();
isRunning[0] = " ";
for (var i=0; i < 3; i++) {
var bool = 'running' + i;
console.log("Running = " + bool);
running = document.getElementById(bool).innerHTML.substring(10,11); //checks if bot running
console.log("running: " + running);
if(isRunning[i] == "1") {
var exph = 'Exph' + i;
var expg = 'Exp' + i;
exphour = document.getElementById(exph).innerHTML; //exphour
currexp = document.getElementById(exp).innerHTML; //current gained exp
exphour =parseInt(exphour);
currexp =parseInt(currexp);
console.log("currexp= " + currexp);
console.log("exphour= " + exphour);
expmin = exphour/60;
console.log("expmin= " + expmin);
expsec = Math.round(expmin/60);
console.log("expsec= " + expsec);
newtotalexp = currexp + expsec;
console.log("newtotalexp= " + newtotalexp);
if (document.getElementById) { document.getElementById(exp).innerHTML = newtotalexp; } //writing new exp
else if (document.lexphouryers) {
document.lexphouryers.theTime.document.write(time);
document.lexphouryers.theTime.document.close(); }
} else {
//Do nothing
return;
}
}
timeout = setTimeout("experiencehour(1)", 1000);
}
}
function variable1hour(var1) {
if(var1 == 0) { //if there is dvar1hourtvar1hour
console.log("var1=0 so no data is present, var1: " + var1);
} else if(var1 == 1){
var isRunning = new Array();
isRunning[0] = " ";
for (var i=0; i < 3; i++) {
var bool = 'running' + i;
console.log("Running = " + bool);
isRunning[i] = document.getElementById(bool).innerHTML.substring(10,11); //checks if bot running
console.log("isRunning = " + isRunning[i]);
if(isRunning[i] == "1") {
var varh = 'Varh' + i;
var varg = 'Var' + i;
console.log("Varh = " + varh);
console.log("Var = " + varg);
var1hour = document.getElementById(varh).innerHTML; //var1hour
currvar1 = document.getElementById(varg).innerHTML; //current gained var1
var1hour =parseInt(var1hour);
currvar1 =parseInt(currvar1);
console.log("currvar1= " + currvar1);
console.log("var1hour= " + var1hour);
var1min = var1hour/60;
console.log("var1min= " + var1min);
var1sec = Math.round(var1min/60);
console.log("var1sec= " + var1sec);
newtotalvar = currvar1 + var1sec;
console.log("newtotalvar= " + newtotalvar);
if (document.getElementById) { document.getElementById(varg).innerHTML = newtotalvar; } //writing new var1
else if (document.lvar1houryers) {
document.lvar1houryers.theTime.document.write(time);
document.lvar1houryers.theTime.document.close();
}
} else {
//Do nothing
return;
}
}
timeout = setTimeout("variable1hour(1)", 1000);
}
}
function stopScript() {
console.log("Stopping script");
clearTimeout(timeout);
}
function startScript(i) {
variable1hour(i);
experiencehour(i);
runningtime(i);
}
Any ideas on how i can get around this so i can get all 3 functions running simultaneously.
I have checked console and im not getting any errors that would stop them from running.
You can't have simultaneously in JS. But you can simulate simultaneous a bit in JS.
Take a look at underscore's defer method.
http://underscorejs.org/#defer
It'd work like this:
Take the loop body and wrap it up in a function
Each iteration through the for loop, make a call to the function using defer
That's basically it. Doing that will allow other functions to "interrupt" any given process (function) and thus "share" the execution thread.
A standard JS implementation w/out defer. I'm trying to simulate the closer of defer. The key takeaway here is that, while the calls still execute in the order that they were queued, all get "started" before any one of them completes. In the case of AJAX async requests, the async response should be able to inject itself between any two loop iterations. You can also set data processing by using slight delays
http://jsfiddle.net/t2z9A/
for(var i = 0; i != 5; ++i)
{
(function(index)
{
document.getElementById('id' + index).innerHTML = 'started...';
setTimeout(function()
{
// kill some time
var str = '';
for(var j = 0; j != 10000000; ++j)
str = str + ' ';
document.getElementById('id' + index).innerHTML = 'Function: 1. Index: ' + index + ' - ' + new Date().getTime();
}, index);
})(i);
}
for(var i = 5; i != 10; ++i)
{
(function(index)
{
document.getElementById('id' + index).innerHTML = 'started...';
setTimeout(function()
{
// kill some time
var str = '';
for(var j = 0; j != 1000000; ++j)
str = str + ' ';
document.getElementById('id' + index).innerHTML = 'Function: 2. Index: ' + index+ ' - ' + new Date().getTime();
}, 1);
})(i);
}