Javascript Date Picker Calendar - javascript

I would like to be able to specify a default date in the date box before the user input.
The JavaScript for the calendar is:
/* ********************************************************************
* Calendar Date Selector - v1.1
* Copyright (c) 2011 - GreyWyvern
*
* - Licenced for free distribution under the BSDL
* http://www.opensource.org/licenses/bsd-license.php
*
* The Calendar Date Selector is the simplest date selection calendar
* you will ever use! No need to insert any javascript into your HTML;
* the script will automatically transform <input> elements with
* attribute type="date" (HTML5) into calendar inputs, respecting both
* min and max attributes as well. Your users then just click the input
* to invoke the calendar input. Works in all major browsers.
*
* Customize the CSS, or date format used (see below), or not! This
* script is completely ready to use as-is. Be sure to include the
* calendar.css stylesheet in your HTML document as well.
*
*/
(function calendarSelector() {
var self = this;
/* ******************************************************************
* Select a Date Format
*
* The calendar script uses the same syntax as the PHP date()
* function, however only the code characters listed below are
* supported; mix and match them as you please with the following
* caveat: The format you use MUST include one (and only one) value
* from each of the Day, Month and Year lists or the calendar will
* not function properly.
*
* Supported date format codes (see http://www.php.net/date):
*
* Day: d, j
* Month: m, n, F, M
* Year: Y, y
* Optional: D, l, S, w
*
* For the day name and month name codes, only the English language
* representations are supported.
*
* Regardless of the date format you choose, the HTML5 date input
* element only accepts source code values in the "Y-m-d" format, so
* be sure to write them as such in your form HTML code. This script
* will rewrite the displayed value using the format given below,
* which will also be the format sent to the server on submission.
*
* NOTE: If a user has javascript disabled, the value will default
* to the Y-m-d format, so it's good practice to allow your server
* side script to accept both.
*
* Example formats:
* - "Y-m-d" => 2010-12-31 (script default)
* - "F jS, Y" => December 31st, 2010
* - 'm/j/y" => 12/31/10
* - 'Y-M-j" => 2010-Dec-31
* - "D M j, Y" => Fri Dec 31, 2010
*
*/
this.format = "D j M Y";
this.weekStart = 0; // 0 = Sunday, 1 = Monday
/* ******************************************************************
* Modified PHP date() implementation in Javascript
* by Carlos R. L. Rodrigues and co. - Much thanks!
* - http://phpjs.org/functions/date
*
*/
this.date = function(format, ts) {
var jsd = (typeof ts === 'undefined') ? new Date() : (ts instanceof Date) ? new Date(ts) : new Date(ts * 1000);
var fChr = /\\?([a-z])/gi, fChrCb = function (t, s) { return f[t] ? f[t]() : s; };
var _pad = function (n, c) { return ((n = n + "").length < c) ? new Array((++c) - n.length).join("0") + n : n; };
var txt_words = [
"Sun", "Mon", "Tues", "Wednes", "Thurs", "Fri", "Satur",
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
], txt_ordin = {1: "st", 2: "nd", 3: "rd", 21: "st", 22: "nd", 23: "rd", 31: "st"};
var f = { // Day
d: function() { return _pad(f.j(), 2); },
D: function() { return f.l().slice(0, 3); },
j: function() { return jsd.getDate(); },
l: function() { return txt_words[f.w()] + 'day'; },
S: function() { return txt_ordin[f.j()] || 'th'; },
w: function() { return jsd.getDay(); },
// Month
F: function() { return txt_words[6 + f.n()]; },
m: function() { return _pad(f.n(), 2); },
M: function() { return f.F().slice(0, 3); },
n: function() { return jsd.getMonth() + 1; },
// Year
Y: function() { return jsd.getFullYear(); },
y: function() { return (f.Y() + "").slice(-2); }
};
return format.replace(fChr, fChrCb);
};
// ***** Parse a date from a string *********************************
this.parse = function(data, rtrn, format) {
if (!data) return rtrn;
if (!format) format = this.format;
var fChr = /\\?([a-z])/gi, fChrCb = function (t, s) { return f[t] ? f[t]() : s; }, ordr = [];
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var f = { // Day
d: function() { ordr.push("d"); return "(\\d\\d)"; },
D: function() { return "(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)"; },
j: function() { ordr.push("d"); return "(\\d\\d?)"; },
l: function() { return "(?:Mon|Tues|Wednes|Thurs|Fri|Satur|Sun)day"; },
S: function() { return "(?:st|nd|rd|th)"; },
w: function() { return "\\d"; },
// Month
F: function() { ordr.push("M"); return "(January|February|March|April|May|June|July|August|September|October|November|December)"; },
m: function() { ordr.push("m"); return "(\\d\\d)"; },
M: function() { ordr.push("M"); return "(" + months.join("|") + ")"; },
n: function() { ordr.push("m"); return "(\\d\\d?)"; },
// Year
Y: function() { ordr.push("y"); return "(\\d{4})"; },
y: function() { ordr.push("y"); return "(\\d\\d)"; }
};
format = format.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
var outp = data.match(new RegExp("^\\s*" + format.replace(fChr, fChrCb) + "\\s*$", ""));
if (outp && ordr.length == 3) {
for (var x = 0, val = []; x < ordr.length; x++) {
switch (ordr[x]) {
case "d": val[2] = parseInt(outp[x + 1], 10); break;
case "m": val[1] = parseInt(outp[x + 1], 10) - 1; break;
case "y": val[0] = parseInt(outp[x + 1], 10); break;
case "M":
for (var y = 0, o = outp[x + 1].slice(0, 3); y < months.length; y++)
if (o == months[y]) val[1] = y;
}
} return new Date(val[0], val[1], val[2]);
} else return rtrn;
};
// ***** Show the calendar ******************************************
this.show = function(elem) {
if (this.cal.parentNode == document.body && elem != this.elem) this.hide(false);
if (this.cal.parentNode != document.body || elem != this.elem) {
this.elem = elem;
this.point = this.parse(elem.value, new Date());
this.build();
var cleft = ctop = 0, obj = elem;
do { cleft += obj.offsetLeft; ctop += obj.offsetTop; } while (obj = obj.offsetParent);
this.cal.style.left = cleft + "px";
this.cal.style.top = (ctop + elem.offsetHeight) + "px";
document.body.appendChild(this.cal);
setTimeout(function() {
_addListener(document.documentElement, 'click', self.listener = function() {
self.hide(false);
}, false);
}, 0);
} else this.hide(false);
};
// ***** Hide the calendar ******************************************
this.hide = function(value) {
if (typeof value == "string") this.elem.value = value;
this.cal = document.body.removeChild(this.cal);
_removeListener(document.documentElement, 'click', this.listener, false);
};
// ***** Build the body of the calendar *****************************
this.build = function() {
var mindt = (mindt = this.parse(this.elem.getAttribute('min'), false, "Y-m-d")) ? this.date("Ymd", mindt) : "";
var maxdt = (maxdt = this.parse(this.elem.getAttribute('max'), false, "Y-m-d")) ? this.date("Ymd", maxdt) : "";
var slctd = (slctd = this.parse(this.elem.value, false)) ? this.date("Ymd", slctd) : "";
this.point.setDate(15);
if (mindt) while (this.date("Ym", this.point) < mindt.substr(0, 6)) this.point.setMonth(this.point.getMonth() + 1);
if (maxdt) while (this.date("Ym", this.point) > maxdt.substr(0, 6)) this.point.setMonth(this.point.getMonth() - 1);
var day = new Date(this.point.getTime()), today = this.date("Ymd");
day.setDate(1);
day.setDate(1 - day.getDay() + this.weekStart);
while (this.cal.tBody.firstChild) this.cal.tBody.removeChild(this.cal.tBody.firstChild);
do {
var tr = document.createElement('tr');
for (var x = 0, ymd; x < 7; x++) {
ymd = this.date("Ymd", day);
var td = document.createElement('td');
td.className = "";
td.title = this.date("l", day);
td.date = new Date(day.getTime());
if ((!mindt || ymd >= mindt) && (!maxdt || ymd <= maxdt)) {
td.className = "valid";
td.onclick = function() { self.hide(self.date(self.format, this.date)); };
} else td.className = "";
if (ymd == slctd) td.className += " selected";
if (day.getMonth() == this.point.getMonth()) {
td.className += " month";
if (ymd == today) td.className += " today";
if (!day.getDay() || day.getDay() == 6) td.className += " weekend";
} td.appendChild(document.createTextNode(day.getDate()));
tr.appendChild(td);
day.setDate(day.getDate() + 1);
} this.cal.tBody.appendChild(tr);
} while (day.getMonth() == this.point.getMonth());
if (mindt) {
mindt = (this.point.getFullYear() - mindt.substr(0, 4)) * 12 - parseInt(mindt.substr(4, 2), 10) + this.point.getMonth() + 1;
this.cal.tHeads[0].className = (mindt < 1) ? "disabled" : "";
this.cal.tHeads[1].getElementsByTagName('strong')[0].className = (mindt < 1) ? "disabled" : "";
} this.cal.tHeads[1].getElementsByTagName('span')[0].firstChild.nodeValue = this.date("F, Y", point);
if (maxdt) {
maxdt = (this.point.getFullYear() - maxdt.substr(0, 4)) * 12 - parseInt(maxdt.substr(4, 2), 10) + this.point.getMonth() + 1;
this.cal.tHeads[2].className = (maxdt > -1) ? "disabled" : "";
this.cal.tHeads[1].getElementsByTagName('em')[0].className = (maxdt > -1) ? "disabled" : "";
}
};
var _addListener = function(elem, type, listener, useCapture) {
if (elem.addEventListener) {
elem.addEventListener(type, listener, useCapture);
} else if (elem.attachEvent) elem.attachEvent('on' + type, listener);
};
var _removeListener = function(elem, type, listener, useCapture) {
if (elem.removeEventListener) {
elem.removeEventListener(type, listener, useCapture);
} else if (elem.detachEvent) elem.detachEvent('on' + type, listener);
};
var _isIE6 = /*#cc_on#if(#_jscript_version == 5.6)!#end#*/false;
// Build the generic calendar container
this.elem = false;
this.cal = document.createElement('div');
this.cal.id = "calendarSelector";
var table = document.createElement('table');
table.cellSpacing = 1;
var thead = document.createElement('thead');
var tr = document.createElement('tr');
var td = document.createElement('td');
td.appendChild(document.createTextNode((_isIE6) ? "<<" : "\u25C2\u25C2"));
td.onclick = function() {
if (this.className != "disabled") {
self.point.setFullYear(self.point.getFullYear() - 1);
self.build(); } };
tr.appendChild(td);
var th = document.createElement('th');
th.colSpan = 5;
var strong = document.createElement('strong');
strong.appendChild(document.createTextNode((_isIE6) ? "<" : "\u25C2"));
strong.onclick = function() {
if (this.className != "disabled") {
self.point.setMonth(self.point.getMonth() - 1);
self.build(); } };
th.appendChild(strong);
var em = document.createElement('em');
em.appendChild(document.createTextNode((_isIE6) ? ">" : "\u25B8"));
em.onclick = function() {
if (this.className != "disabled") {
self.point.setMonth(self.point.getMonth() + 1);
self.build(); } };
th.appendChild(em);
var span = document.createElement('span');
span.appendChild(document.createTextNode("\u2014"));
th.appendChild(span);
tr.appendChild(th);
var td = document.createElement('td');
td.appendChild(document.createTextNode((_isIE6) ? ">>" : "\u25B8\u25B8"));
td.onclick = function() {
if (this.className != "disabled") {
self.point.setFullYear(self.point.getFullYear() + 1);
self.build(); } };
tr.appendChild(td);
thead.appendChild(tr);
table.appendChild(thead);
var tfoot = document.createElement("tfoot");
var tr = document.createElement('tr');
var td = document.createElement('td');
td.colSpan = 2;
td.appendChild(document.createTextNode('Today'));
td.onclick = function() { self.hide(self.date(self.format)); };
tr.appendChild(td);
var td = document.createElement('td');
td.colSpan = 3;
td.appendChild(document.createTextNode('Cancel'));
td.onclick = function() { self.hide(false); };
tr.appendChild(td);
var td = document.createElement('td');
td.colSpan = 2;
td.appendChild(document.createTextNode('Clear'));
td.onclick = function() { self.hide(""); };
tr.appendChild(td);
tfoot.appendChild(tr);
table.appendChild(tfoot);
table.appendChild(this.cal.tBody = document.createElement('tbody'));
this.cal.appendChild(table);
this.cal.tHeads = thead.rows[0].cells;
this.cal.onselectstart = function() { return false; };
this.cal.unselectable = "on";
this.cal.onclick = function(e) {
e = e || event;
if (e.stopPropagation) { e.stopPropagation(); } else e.cancelBubble = true;
};
if (window.opera) this.cal.onmousedown = function() { return false; };
// ***** Apply listeners to applicable inputs
_addListener(window, 'load', function() {
for (var x = 0, inputs = document.getElementsByTagName('input'), val; x < inputs.length; x++) {
if (inputs[x].getAttribute('type') == "date") {
inputs[x].type = "text";
inputs[x].readOnly = "readonly";
inputs[x].onclick = function() { self.show(this); };
if (val = this.parse(inputs[x].value, false, "Y-m-d")) {
var mindt = this.parse(inputs[x].getAttribute('min'), false, "Y-m-d");
var maxdt = this.parse(inputs[x].getAttribute('max'), false, "Y-m-d");
if (mindt && val < mindt) val = mindt;
if (maxdt && val > maxdt) val = maxdt;
inputs[x].value = this.date(this.format, val);
} else inputs[x].value = "";
}
}
}, false);
})();
Then the line of HTML on the page is:
<input name="FromDate" type="date" value="<?php echo 'startdate'; ?>" size="16">
However the script forces the value to be blank.
When the page opens the "startdate" flashes momentarily and then reverts to blank (when the JavaScript has fully loaded).
If I comment out the line to the script, "startdate" appears in the box, no problem.
So it seems that something in the JavaScript reduces the value of the input field to blank or null. As I don't understand JavaScript at all, I hope someone can guide me to the line that needs to be changed.

I figured that there is a bug in the plugin (else it should work as #U and me mentioned).
But as you are already displaying value from php, you can simply comment out the 5th line from the last(else part).

You can replace the php variable startdate into the format of Y-m-d.

Related

Set JavaScript object property with a function

I'm trying to set the property of an object with a function but instead, I get a value of 100 and the slide bar stuck in the middle. What am I doing wrong? Here is my code:
term: {
min: 1,
max: function(){
var period = document.getElementById("duration").value;
if (this.period == "days"){
var value = 31;
} else if(this.period == "months"){
value = 12;
} else {
value = 365;
};
return value;
},
step: 1,
_value: 10,
get value() {
return parseFloat(this._value);
},
set value(val) {
this._value = val;
},
reset: function() {
this._value = 12;
}
},
And this is the result on th UI:
EDIT:
This is how I use min and max:
document.querySelectorAll('.controller-row')
.forEach(function(group) {
var min = inputValues[group.id].min;
var max = inputValues[group.id].max;
var value = inputValues[group.id].value;
var step = inputValues[group.id].step;
var boundary = max ? 100 * (value - min) / (max - min) : 0;
var range = group.querySelector('input[type=range]');
range.setAttribute('style',
'background-image: linear-gradient(90deg, #4098FF 0%, #4098FF ' + boundary + '%, white ' + boundary + '%);'
);
range.min = min;
range.max = max;
range.value = value;
range.step = step;
var textInput = group.querySelector('input[type=number]');
textInput.min = min;
textInput.max = max;
textInput.value = value;
textInput.step = step;
});

Cant call the public method on jquery Plugin

I developed a plugin and when I call the plugin getting an error like Uncaught TypeError: Cannot read property 'convert' of undefined.
Here is my Plugin ,Its not working when I calling in my scripts
( function ($) {
$.siPrifixx = function(element, options) {
var defaults = {
foo: 'bar',
onFoo: function() {
}
}
var plugin = this;
plugin.settings = {
maxDigits: 8,
seperator: true,
decimal: 1,
popUp: false,
countUp:false
}
var $element = $(element),
element = element;
plugin.init = function() {
var value =$(element);
console.log(value);
plugin.settings = $.extend({
}, defaults, options);
var maxDigits = plugin.settings.maxDigits;
console.log(defaults);
if (typeof value === 'string') {
var parts = value.split(",");
var num = parts.join("");
var isNumber = regIsNumber(num)
if(isNumber){
var number = (parseInt(num));
}else{
number = num;
}
}else if (typeof value === 'number'){
number = value
}
var data_max = $(this).attr('data-max-digit');
if(typeof data_max !== 'undefined'){
maxDigits = data_max;
}
var checkNumber = typeof number !== 'undefined' && !isNaN(number) && Math.round(number).toString().length > maxDigits;
if (plugin.settings.popUp && checkNumber) {
$(this).addClass('tooltip', value);
var tootip = $(this).tooltipster({
theme: 'tooltipster-default',
functionInit: function () {
return value
}
})
if(!tootip)
console.log("We couldn't find tooltipster function.Please make sure you have loaded the plugin")
}
if (plugin.settings.countUp && (Math.round(value).toString().length <= maxDigits)) {
var cUp = new countUp(
plugin.settings.countUp, 0, Number(value), 0, 1, null);
cUp.start();
if(!cUp)
console.log("We couldn't find counter function.Please make sure you have loaded the plugin")
}
if (checkNumber) {
var results = plugin.convert(number);
$(this).html(results);
} else {
if (plugin.settings.seperator) {
var cvalue = numberWithCommas(value)
$(this).html(cvalue)
} else {
$(this).html(value)
}
if(typeof value === 'string')
if(checkDate(value)){
$(this).html(value)
}
}
}
plugin.convert = function(number){
var n = settings.decimal
var decPlace = Math.pow(10, n);
var abbrev = ["K", "M", "B", "T"];
for (var i = abbrev.length - 1; i >= 0; i--) {
var size = Math.pow(10, (i + 1) * 3);
if (size <= number) {
number = Math.round(number * decPlace / size) / decPlace;
if ((number == 1000) && (i < abbrev.length - 1)) {
number = 1;
i++;
}
number += abbrev[i];
break;
}
}
console.log(number);
return number;
}
plugin.init();
//use to convert numbers with comma seperated
}
$.fn.siPrifixx = function (options) {
return this.each(function() {
if (undefined == $(this).data('siPrifixx')) {
var plugin = new $.siPrifixx(this,options);
$(this).data('siPrifixx', plugin);
}
});
};
}(jQuery));
I use to call the plugin by $(this).data('siPrifixx').convert(value);});
What is the problem with my code?How can I modify my plugin to gets works?
How can I call convert method in code.
One approach would be to divide plugin into individual portion which each return expected result, then merge the discrete working portions one by one until the full plugin in functional
(function($) {
var settings = {
maxDigits: 8,
seperator: true,
decimal: 0,
popUp: false,
countUp: false
}
function convert(number, options) {
var opts = $.extend(settings, options || {});
var n = opts.decimal;
console.log(opts);
var decPlace = Math.pow(10, n);
var abbrev = ["K", "M", "B", "T"];
for (var i = abbrev.length - 1; i >= 0; i--) {
var size = Math.pow(10, (i + 1) * 3);
if (size <= number) {
number = Math.round(number * decPlace / size) / decPlace;
if ((number == 1000) && (i < abbrev.length - 1)) {
number = 1;
i++;
}
number += abbrev[i];
break;
}
}
this.data("number", number); // set `number` at `.data("number")`
return this; // return `this` for chaining jQuery methods
}
$.fn.convert = convert;
}(jQuery));
var div = $("div");
div.convert(1500000, {decimal:1});
console.log(div.data("number"))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
You should call it like this:
$(this).data('siPrifixx').plugin.convert(value);});

Mouse Over an image to get the color picker [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
HTML:
<img src="../../images/fillpaint3.png" id="fillpaint" alt="fill paint">
I am only able to display the color picker through clicking of a text field
I want to display the color picker after clicking the image not the text box. Any idea how can i do it?
Jquery
var jscolor = {
var e = document.getElementsByTagName('base');
for(var i=0; i<e.length; i+=1) {
if(e[i].href) { base = e[i].href; }
}
var e = document.getElementsByTagName('script');
for(var i=0; i<e.length; i+=1) {
if(e[i].src && /(^|\/)jscolor\.js([?#].*)?$/i.test(e[i].src)) {
var src = new jscolor.URI(e[i].src);
var srcAbs = src.toAbsolute(base);
srcAbs.path = srcAbs.path.replace(/[^\/]+$/, ''); // remove filename
srcAbs.query = null;
srcAbs.fragment = null;
return srcAbs.toString();
}
}
return false;
},
bind : function() {
var matchClass = new RegExp('(^|\\s)('+jscolor.bindClass+')(\\s*(\\{[^}]*\\})|\\s|$)', 'i');
var e = document.getElementsByTagName('input');
for(var i=0; i<e.length; i+=1) {
if(jscolor.isColorAttrSupported && e[i].type.toLowerCase() == 'color') {
// skip inputs of type 'color' if the browser supports this feature
continue;
}
var m;
if(!e[i].color && e[i].className && (m = e[i].className.match(matchClass))) {
var prop = {};
if(m[4]) {
try {
prop = (new Function ('return (' + m[4] + ')'))();
} catch(eInvalidProp) {}
}
e[i].color = new jscolor.color(e[i], prop);
}
}
},
preload : function() {
for(var fn in jscolor.imgRequire) {
if(jscolor.imgRequire.hasOwnProperty(fn)) {
jscolor.loadImage(fn);
}
}
},
images : {
pad : [ 181, 101 ],
sld : [ 16, 101 ],
cross : [ 15, 15 ],
arrow : [ 7, 11 ]
},
imgRequire : {},
imgLoaded : {},
requireImage : function(filename) {
jscolor.imgRequire[filename] = true;
},
loadImage : function(filename) {
if(!jscolor.imgLoaded[filename]) {
jscolor.imgLoaded[filename] = new Image();
jscolor.imgLoaded[filename].src = jscolor.getDir()+filename;
}
},
fetchElement : function(mixed) {
return typeof mixed === 'string' ? document.getElementById(mixed) : mixed;
},
addEvent : function(el, evnt, func) {
if(el.addEventListener) {
el.addEventListener(evnt, func, false);
} else if(el.attachEvent) {
el.attachEvent('on'+evnt, func);
}
},
fireEvent : function(el, evnt) {
if(!el) {
return;
}
if(document.createEvent) {
var ev = document.createEvent('HTMLEvents');
ev.initEvent(evnt, true, true);
el.dispatchEvent(ev);
} else if(document.createEventObject) {
var ev = document.createEventObject();
el.fireEvent('on'+evnt, ev);
} else if(el['on'+evnt]) { // alternatively use the traditional event model (IE5)
el['on'+evnt]();
}
},
getElementPos : function(e) {
var e1=e, e2=e;
var x=0, y=0;
if(e1.offsetParent) {
do {
x += e1.offsetLeft;
y += e1.offsetTop;
} while(e1 = e1.offsetParent);
}
while((e2 = e2.parentNode) && e2.nodeName.toUpperCase() !== 'BODY') {
x -= e2.scrollLeft;
y -= e2.scrollTop;
}
return [x, y];
},
getElementSize : function(e) {
return [e.offsetWidth, e.offsetHeight];
},
getRelMousePos : function(e) {
var x = 0, y = 0;
if (!e) { e = window.event; }
if (typeof e.offsetX === 'number') {
x = e.offsetX;
y = e.offsetY;
} else if (typeof e.layerX === 'number') {
x = e.layerX;
y = e.layerY;
}
return { x: x, y: y };
},
getViewPos : function() {
if(typeof window.pageYOffset === 'number') {
return [window.pageXOffset, window.pageYOffset];
} else if(document.body && (document.body.scrollLeft || document.body.scrollTop)) {
return [document.body.scrollLeft, document.body.scrollTop];
} else if(document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
return [document.documentElement.scrollLeft, document.documentElement.scrollTop];
} else {
return [0, 0];
}
},
getViewSize : function() {
if(typeof window.innerWidth === 'number') {
return [window.innerWidth, window.innerHeight];
} else if(document.body && (document.body.clientWidth || document.body.clientHeight)) {
return [document.body.clientWidth, document.body.clientHeight];
} else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
return [document.documentElement.clientWidth, document.documentElement.clientHeight];
} else {
return [0, 0];
}
},
URI : function(uri) { // See RFC3986
this.scheme = null;
this.authority = null;
this.path = '';
this.query = null;
this.fragment = null;
this.parse = function(uri) {
var m = uri.match(/^(([A-Za-z][0-9A-Za-z+.-]*)(:))?((\/\/)([^\/?#]*))?([^?#]*)((\?)([^#]*))?((#)(.*))?/);
this.scheme = m[3] ? m[2] : null;
this.authority = m[5] ? m[6] : null;
this.path = m[7];
this.query = m[9] ? m[10] : null;
this.fragment = m[12] ? m[13] : null;
return this;
};
this.toString = function() {
var result = '';
if(this.scheme !== null) { result = result + this.scheme + ':'; }
if(this.authority !== null) { result = result + '//' + this.authority; }
if(this.path !== null) { result = result + this.path; }
if(this.query !== null) { result = result + '?' + this.query; }
if(this.fragment !== null) { result = result + '#' + this.fragment; }
return result;
};
this.toAbsolute = function(base) {
var base = new jscolor.URI(base);
var r = this;
var t = new jscolor.URI;
if(base.scheme === null) { return false; }
if(r.scheme !== null && r.scheme.toLowerCase() === base.scheme.toLowerCase()) {
r.scheme = null;
}
if(r.scheme !== null) {
t.scheme = r.scheme;
t.authority = r.authority;
t.path = removeDotSegments(r.path);
t.query = r.query;
} else {
if(r.authority !== null) {
t.authority = r.authority;
t.path = removeDotSegments(r.path);
t.query = r.query;
} else {
if(r.path === '') {
t.path = base.path;
if(r.query !== null) {
t.query = r.query;
} else {
t.query = base.query;
}
} else {
if(r.path.substr(0,1) === '/') {
t.path = removeDotSegments(r.path);
} else {
if(base.authority !== null && base.path === '') {
t.path = '/'+r.path;
} else {
t.path = base.path.replace(/[^\/]+$/,'')+r.path;
}
t.path = removeDotSegments(t.path);
}
t.query = r.query;
}
t.authority = base.authority;
}
t.scheme = base.scheme;
}
t.fragment = r.fragment;
return t;
};
function removeDotSegments(path) {
var out = '';
while(path) {
if(path.substr(0,3)==='../' || path.substr(0,2)==='./') {
path = path.replace(/^\.+/,'').substr(1);
} else if(path.substr(0,3)==='/./' || path==='/.') {
path = '/'+path.substr(3);
} else if(path.substr(0,4)==='/../' || path==='/..') {
path = '/'+path.substr(4);
out = out.replace(/\/?[^\/]*$/, '');
} else if(path==='.' || path==='..') {
path = '';
} else {
var rm = path.match(/^\/?[^\/]*/)[0];
path = path.substr(rm.length);
out = out + rm;
}
}
return out;
}
if(uri) {
this.parse(uri);
}
},
//
// Usage example:
// var myColor = new jscolor.color(myInputElement)
//
color : function(target, prop) {
this.required = true; // refuse empty values?
this.adjust = true; // adjust value to uniform notation?
this.hash = false; // prefix color with # symbol?
this.caps = true; // uppercase?
this.slider = true; // show the value/saturation slider?
this.valueElement = target; // value holder
this.styleElement = target; // where to reflect current color
this.onImmediateChange = null; // onchange callback (can be either string or function)
this.hsv = [0, 0, 1]; // read-only 0-6, 0-1, 0-1
this.rgb = [1, 1, 1]; // read-only 0-1, 0-1, 0-1
this.minH = 0; // read-only 0-6
this.maxH = 6; // read-only 0-6
this.minS = 0; // read-only 0-1
this.maxS = 1; // read-only 0-1
this.minV = 0; // read-only 0-1
this.maxV = 1; // read-only 0-1
this.pickerOnfocus = true; // display picker on focus?
this.pickerMode = 'HSV'; // HSV | HVS
this.pickerPosition = 'bottom'; // left | right | top | bottom
this.pickerSmartPosition = true; // automatically adjust picker position when necessary
this.pickerFixedPosition = false; // set to true to stop picker from moving on scroll
this.pickerButtonHeight = 20; // px
this.pickerClosable = false;
this.pickerCloseText = 'Close';
this.pickerButtonColor = 'ButtonText'; // px
this.pickerFace = 10; // px
this.pickerFaceColor = 'ThreeDFace'; // CSS color
this.pickerBorder = 1; // px
this.pickerBorderColor = 'ThreeDHighlight ThreeDShadow ThreeDShadow ThreeDHighlight'; // CSS color
this.pickerInset = 1; // px
this.pickerInsetColor = 'ThreeDShadow ThreeDHighlight ThreeDHighlight ThreeDShadow'; // CSS color
this.pickerZIndex = 10000;
for(var p in prop) {
if(prop.hasOwnProperty(p)) {
this[p] = prop[p];
}
}
this.hidePicker = function() {
if(isPickerOwner()) {
removePicker();
}
};
this.showPicker = function() {
if(!isPickerOwner()) {
var tp = jscolor.getElementPos(target); // target pos
var ts = jscolor.getElementSize(target); // target size
var vp = jscolor.getViewPos(); // view pos
var vs = jscolor.getViewSize(); // view size
var ps = getPickerDims(this); // picker size
var a, b, c;
switch(this.pickerPosition.toLowerCase()) {
case 'left': a=1; b=0; c=-1; break;
case 'right':a=1; b=0; c=1; break;
case 'top': a=0; b=1; c=-1; break;
default: a=0; b=1; c=1; break;
}
var l = (ts[b]+ps[b])/2;
// picker pos
if (!this.pickerSmartPosition) {
var pp = [
tp[a],
tp[b]+ts[b]-l+l*c
];
} else {
var pp = [
-vp[a]+tp[a]+ps[a] > vs[a] ?
(-vp[a]+tp[a]+ts[a]/2 > vs[a]/2 && tp[a]+ts[a]-ps[a] >= 0 ? tp[a]+ts[a]-ps[a] : tp[a]) :
tp[a],
-vp[b]+tp[b]+ts[b]+ps[b]-l+l*c > vs[b] ?
(-vp[b]+tp[b]+ts[b]/2 > vs[b]/2 && tp[b]+ts[b]-l-l*c >= 0 ? tp[b]+ts[b]-l-l*c : tp[b]+ts[b]-l+l*c) :
(tp[b]+ts[b]-l+l*c >= 0 ? tp[b]+ts[b]-l+l*c : tp[b]+ts[b]-l-l*c)
];
}
drawPicker(pp[a], pp[b]);
}
};
this.importColor = function() {
if(!valueElement) {
this.exportColor();
} else {
if(!this.adjust) {
if(!this.fromString(valueElement.value, leaveValue)) {
styleElement.style.backgroundImage = styleElement.jscStyle.backgroundImage;
styleElement.style.backgroundColor = styleElement.jscStyle.backgroundColor;
styleElement.style.color = styleElement.jscStyle.color;
this.exportColor(leaveValue | leaveStyle);
}
} else if(!this.required && /^\s*$/.test(valueElement.value)) {
valueElement.value = '';
styleElement.style.backgroundImage = styleElement.jscStyle.backgroundImage;
styleElement.style.backgroundColor = styleElement.jscStyle.backgroundColor;
styleElement.style.color = styleElement.jscStyle.color;
this.exportColor(leaveValue | leaveStyle);
} else if(this.fromString(valueElement.value)) {
// OK
} else {
this.exportColor();
}
}
};
this.exportColor = function(flags) {
if(!(flags & leaveValue) && valueElement) {
var value = this.toString();
if(this.caps) { value = value.toUpperCase(); }
if(this.hash) { value = '#'+value; }
valueElement.value = value;
}
if(!(flags & leaveStyle) && styleElement) {
styleElement.style.backgroundImage = "none";
styleElement.style.backgroundColor =
'#'+this.toString();
styleElement.style.color =
0.213 * this.rgb[0] +
0.715 * this.rgb[1] +
0.072 * this.rgb[2]
< 0.5 ? '#FFF' : '#000';
}
if(!(flags & leavePad) && isPickerOwner()) {
redrawPad();
}
if(!(flags & leaveSld) && isPickerOwner()) {
redrawSld();
}
};
this.fromHSV = function(h, s, v, flags) { // null = don't change
if(h !== null) { h = Math.max(0.0, this.minH, Math.min(6.0, this.maxH, h)); }
if(s !== null) { s = Math.max(0.0, this.minS, Math.min(1.0, this.maxS, s)); }
if(v !== null) { v = Math.max(0.0, this.minV, Math.min(1.0, this.maxV, v)); }
this.rgb = HSV_RGB(
h===null ? this.hsv[0] : (this.hsv[0]=h),
s===null ? this.hsv[1] : (this.hsv[1]=s),
v===null ? this.hsv[2] : (this.hsv[2]=v)
);
this.exportColor(flags);
};
this.fromRGB = function(r, g, b, flags) { // null = don't change
if(r !== null) { r = Math.max(0.0, Math.min(1.0, r)); }
if(g !== null) { g = Math.max(0.0, Math.min(1.0, g)); }
if(b !== null) { b = Math.max(0.0, Math.min(1.0, b)); }
var hsv = RGB_HSV(
r===null ? this.rgb[0] : r,
g===null ? this.rgb[1] : g,
b===null ? this.rgb[2] : b
);
if(hsv[0] !== null) {
this.hsv[0] = Math.max(0.0, this.minH, Math.min(6.0, this.maxH, hsv[0]));
}
if(hsv[2] !== 0) {
this.hsv[1] = hsv[1]===null ? null : Math.max(0.0, this.minS, Math.min(1.0, this.maxS, hsv[1]));
}
this.hsv[2] = hsv[2]===null ? null : Math.max(0.0, this.minV, Math.min(1.0, this.maxV, hsv[2]));
// update RGB according to final HSV, as some values might be trimmed
var rgb = HSV_RGB(this.hsv[0], this.hsv[1], this.hsv[2]);
this.rgb[0] = rgb[0];
this.rgb[1] = rgb[1];
this.rgb[2] = rgb[2];
this.exportColor(flags);
};
this.fromString = function(hex, flags) {
var m = hex.match(/^\W*([0-9A-F]{3}([0-9A-F]{3})?)\W*$/i);
if(!m) {
return false;
} else {
if(m[1].length === 6) { // 6-char notation
this.fromRGB(
parseInt(m[1].substr(0,2),16) / 255,
parseInt(m[1].substr(2,2),16) / 255,
parseInt(m[1].substr(4,2),16) / 255,
flags
);
} else { // 3-char notation
this.fromRGB(
parseInt(m[1].charAt(0)+m[1].charAt(0),16) / 255,
parseInt(m[1].charAt(1)+m[1].charAt(1),16) / 255,
parseInt(m[1].charAt(2)+m[1].charAt(2),16) / 255,
flags
);
}
return true;
}
};
this.toString = function() {
return (
(0x100 | Math.round(255*this.rgb[0])).toString(16).substr(1) +
(0x100 | Math.round(255*this.rgb[1])).toString(16).substr(1) +
(0x100 | Math.round(255*this.rgb[2])).toString(16).substr(1)
);
};
function RGB_HSV(r, g, b) {
var n = Math.min(Math.min(r,g),b);
var v = Math.max(Math.max(r,g),b);
var m = v - n;
if(m === 0) { return [ null, 0, v ]; }
var h = r===n ? 3+(b-g)/m : (g===n ? 5+(r-b)/m : 1+(g-r)/m);
return [ h===6?0:h, m/v, v ];
}
function HSV_RGB(h, s, v) {
if(h === null) { return [ v, v, v ]; }
var i = Math.floor(h);
var f = i%2 ? h-i : 1-(h-i);
var m = v * (1 - s);
var n = v * (1 - s*f);
switch(i) {
case 6:
case 0: return [v,n,m];
case 1: return [n,v,m];
case 2: return [m,v,n];
case 3: return [m,n,v];
case 4: return [n,m,v];
case 5: return [v,m,n];
}
}
function removePicker() {
delete jscolor.picker.owner;
document.getElementsByTagName('body')[0].removeChild(jscolor.picker.boxB);
}
function drawPicker(x, y) {
if(!jscolor.picker) {
jscolor.picker = {
box : document.createElement('div'),
boxB : document.createElement('div'),
pad : document.createElement('div'),
padB : document.createElement('div'),
padM : document.createElement('div'),
sld : document.createElement('div'),
sldB : document.createElement('div'),
sldM : document.createElement('div'),
btn : document.createElement('div'),
btnS : document.createElement('span'),
btnT : document.createTextNode(THIS.pickerCloseText)
};
for(var i=0,segSize=4; i<jscolor.images.sld[1]; i+=segSize) {
var seg = document.createElement('div');
seg.style.height = segSize+'px';
seg.style.fontSize = '1px';
seg.style.lineHeight = '0';
jscolor.picker.sld.appendChild(seg);
}
jscolor.picker.sldB.appendChild(jscolor.picker.sld);
jscolor.picker.box.appendChild(jscolor.picker.sldB);
jscolor.picker.box.appendChild(jscolor.picker.sldM);
jscolor.picker.padB.appendChild(jscolor.picker.pad);
jscolor.picker.box.appendChild(jscolor.picker.padB);
jscolor.picker.box.appendChild(jscolor.picker.padM);
jscolor.picker.btnS.appendChild(jscolor.picker.btnT);
jscolor.picker.btn.appendChild(jscolor.picker.btnS);
jscolor.picker.box.appendChild(jscolor.picker.btn);
jscolor.picker.boxB.appendChild(jscolor.picker.box);
}
var p = jscolor.picker;
// controls interaction
p.box.onmouseup =
p.box.onmouseout = function() { target.focus(); };
p.box.onmousedown = function() { abortBlur=true; };
p.box.onmousemove = function(e) {
if (holdPad || holdSld) {
holdPad && setPad(e);
holdSld && setSld(e);
if (document.selection) {
document.selection.empty();
} else if (window.getSelection) {
window.getSelection().removeAllRanges();
}
dispatchImmediateChange();
}
};
if('ontouchstart' in window) { // if touch device
var handle_touchmove = function(e) {
var event={
'offsetX': e.touches[0].pageX-touchOffset.X,
'offsetY': e.touches[0].pageY-touchOffset.Y
};
if (holdPad || holdSld) {
holdPad && setPad(event);
holdSld && setSld(event);
dispatchImmediateChange();
}
e.stopPropagation(); // prevent move "view" on broswer
e.preventDefault(); // prevent Default - Android Fix (else android generated only 1-2 touchmove events)
};
p.box.removeEventListener('touchmove', handle_touchmove, false)
p.box.addEventListener('touchmove', handle_touchmove, false)
}
p.padM.onmouseup =
p.padM.onmouseout = function() { if(holdPad) { holdPad=false; jscolor.fireEvent(valueElement,'change'); } };
p.padM.onmousedown = function(e) {
// if the slider is at the bottom, move it up
switch(modeID) {
case 0: if (THIS.hsv[2] === 0) { THIS.fromHSV(null, null, 1.0); }; break;
case 1: if (THIS.hsv[1] === 0) { THIS.fromHSV(null, 1.0, null); }; break;
}
holdSld=false;
holdPad=true;
setPad(e);
dispatchImmediateChange();
};
if('ontouchstart' in window) {
p.padM.addEventListener('touchstart', function(e) {
touchOffset={
'X': e.target.offsetParent.offsetLeft,
'Y': e.target.offsetParent.offsetTop
};
this.onmousedown({
'offsetX':e.touches[0].pageX-touchOffset.X,
'offsetY':e.touches[0].pageY-touchOffset.Y
});
});
}
p.sldM.onmouseup =
p.sldM.onmouseout = function() { if(holdSld) { holdSld=false; jscolor.fireEvent(valueElement,'change'); } };
p.sldM.onmousedown = function(e) {
holdPad=false;
holdSld=true;
setSld(e);
dispatchImmediateChange();
};
if('ontouchstart' in window) {
p.sldM.addEventListener('touchstart', function(e) {
touchOffset={
'X': e.target.offsetParent.offsetLeft,
'Y': e.target.offsetParent.offsetTop
};
this.onmousedown({
'offsetX':e.touches[0].pageX-touchOffset.X,
'offsetY':e.touches[0].pageY-touchOffset.Y
});
});
}
// picker
var dims = getPickerDims(THIS);
p.box.style.width = dims[0] + 'px';
p.box.style.height = dims[1] + 'px';
// picker border
p.boxB.style.position = THIS.pickerFixedPosition ? 'fixed' : 'absolute';
p.boxB.style.clear = 'both';
p.boxB.style.left = x+'px';
p.boxB.style.top = y+'px';
p.boxB.style.zIndex = THIS.pickerZIndex;
p.boxB.style.border = THIS.pickerBorder+'px solid';
p.boxB.style.borderColor = THIS.pickerBorderColor;
p.boxB.style.background = THIS.pickerFaceColor;
// pad image
p.pad.style.width = jscolor.images.pad[0]+'px';
p.pad.style.height = jscolor.images.pad[1]+'px';
// pad border
p.padB.style.position = 'absolute';
p.padB.style.left = THIS.pickerFace+'px';
p.padB.style.top = THIS.pickerFace+'px';
p.padB.style.border = THIS.pickerInset+'px solid';
p.padB.style.borderColor = THIS.pickerInsetColor;
// pad mouse area
p.padM.style.position = 'absolute';
p.padM.style.left = '0';
p.padM.style.top = '0';
p.padM.style.width = THIS.pickerFace + 2*THIS.pickerInset + jscolor.images.pad[0] + jscolor.images.arrow[0] + 'px';
p.padM.style.height = p.box.style.height;
p.padM.style.cursor = 'crosshair';
// slider image
p.sld.style.overflow = 'hidden';
p.sld.style.width = jscolor.images.sld[0]+'px';
p.sld.style.height = jscolor.images.sld[1]+'px';
// slider border
p.sldB.style.display = THIS.slider ? 'block' : 'none';
p.sldB.style.position = 'absolute';
p.sldB.style.right = THIS.pickerFace+'px';
p.sldB.style.top = THIS.pickerFace+'px';
p.sldB.style.border = THIS.pickerInset+'px solid';
p.sldB.style.borderColor = THIS.pickerInsetColor;
// slider mouse area
p.sldM.style.display = THIS.slider ? 'block' : 'none';
p.sldM.style.position = 'absolute';
p.sldM.style.right = '0';
p.sldM.style.top = '0';
p.sldM.style.width = jscolor.images.sld[0] + jscolor.images.arrow[0] + THIS.pickerFace + 2*THIS.pickerInset + 'px';
p.sldM.style.height = p.box.style.height;
try {
p.sldM.style.cursor = 'pointer';
} catch(eOldIE) {
p.sldM.style.cursor = 'hand';
}
// "close" button
function setBtnBorder() {
var insetColors = THIS.pickerInsetColor.split(/\s+/);
var pickerOutsetColor = insetColors.length < 2 ? insetColors[0] : insetColors[1] + ' ' + insetColors[0] + ' ' + insetColors[0] + ' ' + insetColors[1];
p.btn.style.borderColor = pickerOutsetColor;
}
p.btn.style.display = THIS.pickerClosable ? 'block' : 'none';
p.btn.style.position = 'absolute';
p.btn.style.left = THIS.pickerFace + 'px';
p.btn.style.bottom = THIS.pickerFace + 'px';
p.btn.style.padding = '0 15px';
p.btn.style.height = '18px';
p.btn.style.border = THIS.pickerInset + 'px solid';
setBtnBorder();
p.btn.style.color = THIS.pickerButtonColor;
p.btn.style.font = '12px sans-serif';
p.btn.style.textAlign = 'center';
try {
p.btn.style.cursor = 'pointer';
} catch(eOldIE) {
p.btn.style.cursor = 'hand';
}
p.btn.onmousedown = function () {
THIS.hidePicker();
};
p.btnS.style.lineHeight = p.btn.style.height;
// load images in optimal order
switch(modeID) {
case 0: var padImg = 'hs.png'; break;
case 1: var padImg = 'hv.png'; break;
}
p.padM.style.backgroundImage = "url('"+jscolor.getDir()+"cross.gif')";
p.padM.style.backgroundRepeat = "no-repeat";
p.sldM.style.backgroundImage = "url('"+jscolor.getDir()+"arrow.gif')";
p.sldM.style.backgroundRepeat = "no-repeat";
p.pad.style.backgroundImage = "url('"+jscolor.getDir()+padImg+"')";
p.pad.style.backgroundRepeat = "no-repeat";
p.pad.style.backgroundPosition = "0 0";
// place pointers
redrawPad();
redrawSld();
jscolor.picker.owner = THIS;
document.getElementsByTagName('body')[0].appendChild(p.boxB);
}
function getPickerDims(o) {
var dims = [
2*o.pickerInset + 2*o.pickerFace + jscolor.images.pad[0] +
(o.slider ? 2*o.pickerInset + 2*jscolor.images.arrow[0] + jscolor.images.sld[0] : 0),
o.pickerClosable ?
4*o.pickerInset + 3*o.pickerFace + jscolor.images.pad[1] + o.pickerButtonHeight :
2*o.pickerInset + 2*o.pickerFace + jscolor.images.pad[1]
];
return dims;
}
function redrawPad() {
// redraw the pad pointer
switch(modeID) {
case 0: var yComponent = 1; break;
case 1: var yComponent = 2; break;
}
var x = Math.round((THIS.hsv[0]/6) * (jscolor.images.pad[0]-1));
var y = Math.round((1-THIS.hsv[yComponent]) * (jscolor.images.pad[1]-1));
jscolor.picker.padM.style.backgroundPosition =
(THIS.pickerFace+THIS.pickerInset+x - Math.floor(jscolor.images.cross[0]/2)) + 'px ' +
(THIS.pickerFace+THIS.pickerInset+y - Math.floor(jscolor.images.cross[1]/2)) + 'px';
// redraw the slider image
var seg = jscolor.picker.sld.childNodes;
switch(modeID) {
case 0:
var rgb = HSV_RGB(THIS.hsv[0], THIS.hsv[1], 1);
for(var i=0; i<seg.length; i+=1) {
seg[i].style.backgroundColor = 'rgb('+
(rgb[0]*(1-i/seg.length)*100)+'%,'+
(rgb[1]*(1-i/seg.length)*100)+'%,'+
(rgb[2]*(1-i/seg.length)*100)+'%)';
}
break;
case 1:
var rgb, s, c = [ THIS.hsv[2], 0, 0 ];
var i = Math.floor(THIS.hsv[0]);
var f = i%2 ? THIS.hsv[0]-i : 1-(THIS.hsv[0]-i);
switch(i) {
case 6:
case 0: rgb=[0,1,2]; break;
case 1: rgb=[1,0,2]; break;
case 2: rgb=[2,0,1]; break;
case 3: rgb=[2,1,0]; break;
case 4: rgb=[1,2,0]; break;
case 5: rgb=[0,2,1]; break;
}
for(var i=0; i<seg.length; i+=1) {
s = 1 - 1/(seg.length-1)*i;
c[1] = c[0] * (1 - s*f);
c[2] = c[0] * (1 - s);
seg[i].style.backgroundColor = 'rgb('+
(c[rgb[0]]*100)+'%,'+
(c[rgb[1]]*100)+'%,'+
(c[rgb[2]]*100)+'%)';
}
break;
}
}
function redrawSld() {
// redraw the slider pointer
switch(modeID) {
case 0: var yComponent = 2; break;
case 1: var yComponent = 1; break;
}
var y = Math.round((1-THIS.hsv[yComponent]) * (jscolor.images.sld[1]-1));
jscolor.picker.sldM.style.backgroundPosition =
'0 ' + (THIS.pickerFace+THIS.pickerInset+y - Math.floor(jscolor.images.arrow[1]/2)) + 'px';
}
function isPickerOwner() {
return jscolor.picker && jscolor.picker.owner === THIS;
}
function blurTarget() {
if(valueElement === target) {
THIS.importColor();
}
if(THIS.pickerOnfocus) {
THIS.hidePicker();
}
}
function blurValue() {
if(valueElement !== target) {
THIS.importColor();
}
}
function setPad(e) {
var mpos = jscolor.getRelMousePos(e);
var x = mpos.x - THIS.pickerFace - THIS.pickerInset;
var y = mpos.y - THIS.pickerFace - THIS.pickerInset;
switch(modeID) {
case 0: THIS.fromHSV(x*(6/(jscolor.images.pad[0]-1)), 1 - y/(jscolor.images.pad[1]-1), null, leaveSld); break;
case 1: THIS.fromHSV(x*(6/(jscolor.images.pad[0]-1)), null, 1 - y/(jscolor.images.pad[1]-1), leaveSld); break;
}
}
function setSld(e) {
var mpos = jscolor.getRelMousePos(e);
var y = mpos.y - THIS.pickerFace - THIS.pickerInset;
switch(modeID) {
case 0: THIS.fromHSV(null, null, 1 - y/(jscolor.images.sld[1]-1), leavePad); break;
case 1: THIS.fromHSV(null, 1 - y/(jscolor.images.sld[1]-1), null, leavePad); break;
}
}
function dispatchImmediateChange() {
if (THIS.onImmediateChange) {
var callback;
if (typeof THIS.onImmediateChange === 'string') {
callback = new Function (THIS.onImmediateChange);
} else {
callback = THIS.onImmediateChange;
}
callback.call(THIS);
}
}
var THIS = this;
var modeID = this.pickerMode.toLowerCase()==='hvs' ? 1 : 0;
var abortBlur = false;
var
valueElement = jscolor.fetchElement(this.valueElement),
styleElement = jscolor.fetchElement(this.styleElement);
var
holdPad = false,
holdSld = false,
touchOffset = {};
var
leaveValue = 1<<0,
leaveStyle = 1<<1,
leavePad = 1<<2,
leaveSld = 1<<3;
jscolor.isColorAttrSupported = false;
var el = document.createElement('input');
if(el.setAttribute) {
el.setAttribute('type', 'color');
if(el.type.toLowerCase() == 'color') {
jscolor.isColorAttrSupported = true;
}
}
// target
jscolor.addEvent(target, 'focus', function() {
if(THIS.pickerOnfocus) { THIS.showPicker(); }
});
jscolor.addEvent(target, 'blur', function() {
if(!abortBlur) {
window.setTimeout(function(){ abortBlur || blurTarget(); abortBlur=false; }, 0);
} else {
abortBlur = false;
}
});
// valueElement
if(valueElement) {
var updateField = function() {
THIS.fromString(valueElement.value, leaveValue);
dispatchImmediateChange();
};
jscolor.addEvent(valueElement, 'keyup', updateField);
jscolor.addEvent(valueElement, 'input', updateField);
jscolor.addEvent(valueElement, 'blur', blurValue);
valueElement.setAttribute('autocomplete', 'off');
}
// styleElement
if(styleElement) {
styleElement.jscStyle = {
backgroundImage : styleElement.style.backgroundImage,
backgroundColor : styleElement.style.backgroundColor,
color : styleElement.style.color
};
}
// require images
switch(modeID) {
case 0: jscolor.requireImage('hs.png'); break;
case 1: jscolor.requireImage('hv.png'); break;
}
jscolor.requireImage('cross.gif');
jscolor.requireImage('arrow.gif');
this.importColor();
}
};
jscolor.install();
Please take a look at my jquery. Not all are here, stackoverflow dont allow me to insert everything
It's not the officially (I think that there is no officially way) but it's working.
document.querySelector('button').onmouseenter = function() {
document.querySelector('input')._jscLinkedInstance.show();
}
<script src="http://jscolor.com/release/2.0/jscolor-2.0.4/jscolor.js"></script>
Color: <input class="jscolor" value="ab2567" tabindex="-1" />
<button>Open</button>
The _jscLinkedInstanceobject store the data of the plugin with properties and functions.
Note: This demo is for mouseenter event (for mouse-over requested in the title: Mouse Over an image..) If you want to trigger the click event of the image (button in the snippet) by your question (I want to display the color picker after clicking the image) just replace the onmouseenter with onclick.

Can't validate this! Validation process keeps stopping

I'm having problems validating this piece of javascript code. JSlint keeps stopping after the first for instruction and I can't seem to figure out why. It seems as if the validator is picking on warnings rather than errors (such as "use space instead of tabs" or "expected +=1 instead of ++" which all seem fine to me). Also, I'm not sure if it does what it's supposed to but I can't check that until I get the validation done.
var prompt = document.getElementById("prompt");
var response = document.getElementById("response");
var warning = document.getElementById("warning");
var fixation = 'fixPlus.jpg';
var cueImage = ['fixPlus.jpg', 'midCue.jpg', 'bothCue.jpg', 'topCue.jpg', 'botCue.jpg'];
//images for stimuli were taken from wheedesign.com
var stImage = ['T_L_N.jpg', 'T_L_C.jpg', 'T_L_I.jpg', 'T_R_N.jpg', 'T_R_C.jpg', 'T_R_I.jpg', 'B_L_N.jpg', 'B_L_C.jpg', 'B_L_I.jpg', 'B_R_N.jpg', 'B_R_C.jpg', 'B_R_I.jpg'];
var condIdx[1];
var i;
for (i = 2, i <= 47; i++) {
condIdx.push(i);
}
var cueType = ['0', '1', '2']; //I will use a repetitive instruction instead of writing 000,111, etc
for (i = 0; i < 11; i++) {
cuetype[i] = 0;
}
for (i = 12; i < 23; i++) {
cueType[i] = 1;
}
for (i = 24; i < 35; i++) {
cueType[i] = 2;
}
for (i = 36; i < 41; i++) {
cueType[i] = 3;
}
for (i = 42; i < 47; i++) {
cueType[i] = 4;
}
var stType = ['0', '1', '2', '3', '4', '5', '6', '7'];
var ansKey = ['Z', 'Z', 'Z', 'Z', 'Z', 'Z', 'M', 'M', 'M', 'M', 'M', 'M'];
var promptTxt = 'Press Z for left and M for right';
var invalidTxt = ' -- Invalid key press!!!';
var correctTxt = 'correct answer!';
var incorrectTxt = 'incorrect answer!'
var waitTxt = 'Wait for the prompt!';
var tooSlow = 'Too slow!';
var toa = 400; //trial onset asynchrony in ms
var preCueFixTime[500, 600, 700, 800, 900, 1000, 1100, 1200]; //pre-cue fixation
var cueTime = 100; // cue in ms
var postCueTime = 400; //post-cue fixation
var maxStTime = 1500; //stimulus display (until a key is pressed or 1500ms has lapsed)
var promptTime = 1500; // duration of response prompt in ms
var nTrial = isPractice ? 1 : 24;
var trialCounter = 0; //to keep track of progress
var remainStr = ''; //remaining trials
var doneStr = ''; //trials completed
var indxChar = '='; //character used to indicate a trial
var remainColor = 'LightBlue'; //color to display remainStr
var doneColor = 'Navy';
var progTxt = 'Progress: '.fontcolor(doneColor);
var rspArr = []; //to store responses
var cssFile = '<link rel = "stylesheet" type = "text/css" href = "rngStyle.css">';
var blocks = 0;
function block_initiation() {
if (blocks < 7) {
warning.innerHTML = '';
response.innerHTML = '';
object.onclick = "trialBlock()" + 'Click here to begin a block of trials!';
blocks++;
updateProgress();
} else {
submitData();
}
}
function trialBlock() {
"use strict";
condIdx = shuffle(condIdx);
preCueFixTime = shuffle(preCueFixTime);
cueImage = shuffle(cueImage);
for (i = 0; i < 6; i++) {
var theTask = setInterval(function () {
aTrial();
}, toa);
}
}
function aTrial() {
"use strict";
if (trialCounter < nTrial) {
warning.innerHTML = '';
response.innerHTML = '';
getKeypress();
trialCounter++;
updateProgress();
} else {
submitData();
}
}
function getKeypress() {
"use strict";
rspArr.push(0);
// fixation - cue - fixation - stimulus - key press/too slow
var interval = window.setInterval(function () {
if (fixation.display == 'hidden') {
fixation.style.visibility = 'visible';
} else {
fixation.style.visibility = 'hidden';
}
}, preCueFixTime[trialCounter]); //display initial fixation
if (cueImage[trialCounter].display == 'hidden') {
cueImage[trialCounter].style.visibility = 'visible';
} else {
cueImage[trialCounter].style.visibility = 'hidden';
}
}, 100); //shows cue display for 100ms
prompt.innerHTML = promptTxt; //show the prompt text
setTimeout(function () {
prompt.innerHTML = '';
}, promptTime);
if (stImage[condIdx[trialCounter]].display == 'hidden') {
stImage[condIdx[trialCounter].style.visibility = 'visible';
} else {
stImage[condIdx[trialCounter]].style.visibility = 'hidden';
}
}, 1500);
setTimeout(function () {
tooSlow.innerHTML = '';
}, tooSlow);
var inputRecorded = false;
document.onkeydown = function (e) {
if (inputRecorded) {
warning.innerHTML = waitTxt;
cueImage[trialCounter].style.visibility = 'hidden';
return false; //to cancel the event
}
e = e || window.event;
var key_press = String.fromCharCode(e.keyCode);
var regex = /[MZ]/;
condIdx[trialCounter].innerHTML = '';
//stImage[indeces 1 to 6] should be Z and stImage[7-12] should be M
var stStart = new Date();
fixation + cueImage[trialCounter] + fixation + stImage[condIdx[trialCounter]];
setTimeout(function () {
fixation.innerHTML = '';
}, preCueFixTime[trialCounter]); //this will still show preCueFixTime in ascending order
if (key_press.search(regex) > -1) {
var stEnd = new Date();
var RT = stEnd.getTime() - stStart.getTime();
//something was pressed
if (condIdx[trialCount] < 7 && key_press == 'Z'
OR condIdx[trialCount] >= 7 && key_press == 'M') {
//correct!
var correct = true;
trialCond = [cond Idx, cueType, correct, RT];
rspArr[trialCount] = trialCond.join();
response.innerHTML = key_press;
clearInterval(tooSlow); // cancel Too Slow
clearInterval(stImage[trialCounter]); //cancel stimulus display
warning.innerHTML = correctTxt;
} else {
//incorrect!
var correct = false;
rspArr[rspArr.length - 1] = key_press;
response.innerHTML = key_press;
clearInterval(tooSlow); // cancel Too Slow
clearInterval(stImage[trialCounter]); //cancel stimulus display
warning.innerHTML = incorrectTxt;
}
} else {
warning.innerHTML = key_press + invalidTxt;
}
inputRecorded = true;
}; //document.onkeydown
}
function updateProgress() {
"use strict";
//alert (trialCounter + ' ' + remainStr);
if (trialCounter === 0) {
for (var i = 0; i < nTrial; i++) {
remainStr += indxChar;
}
} else {
doneStr += indxChar;
remainStr = remainStr.slice(0, -1);
}
progress.innerHTML = progTxt + doneStr.fontcolor(doneColor) + remainStr.fontcolor(remainColor);
}
function checkProgress() {
"use strict";
var j, tot = 0,
n = rspArr.length;
//alert(tot + ' ' + n);
for (j = n - 5; j < n; j++) {
if (rspArr[j] > 0) {
tot++;
}
}
var actionAttr, fbkTxtm, valueAttr;
if (tot > 3) {
actionAttr = 'action="rng04Task.php"';
fbkTxt = '<h2>Good! That ends the practice. </h2>';
valueAttr = 'value="Click here to formally begin the task"';
} else {
actionAttr = 'action="rng03Practice.php"';
fbkTxt = '<h2>You are not quite in sync with the prompts </h2>' + '<h2> Please try again </h2>';
valueAttr = 'value="Click here to have some more practice"';
}
document.write(cssFile +
'<form class="center"' + actionAttr + '>' + fbkTxt + '<input class = "myButton" type="submit"' + valueAttr + '>' + '</form>');
//alert(cssFile +
//'<form class="center"' + actionAttr + '>' + fbkTxt + '<input class = "myButton" type="submit"' + valueAttr + '>' + '</form>');
}
function shuffle(arr) {
"use strict";
for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return arr;
//function taken and adapted from http://jsfromhell.com/array/shuffle
};
function submitData() {
"use strict";
}
I suspect it's failing on:
var condIdx[1];
As I don't think that's valid js syntax. You are attempting to declare a variable name, and provide a size/or access an index, in the same line, without an equality statement?

How to close a datepicker on javascript when click somewhere outside the div?

I downloaded a simple datepicker by Marc Grabanski. I want to add him a function, the thing is I don't know javascript.
I want to close the Calendar Div when I click somewhere outside, like if I pressed the close button.
HTML:
<head>
<script src="calendar.js"></script>
<link href="calendar.css" rel="stylesheet">
</head>
<body>
<div id="calendarDiv"></div>
<h1>Modificado a partir do Original de Marc Grabanski</h1>
<br/>
<label>Data:</label>
<input type="text" class="calendarSelectDate"/>
</body>
Javascript:
/*!
* Clean Calendar
* Copyright 2007-2009 Marc Grabanski (m#marcgrabanski.com) http://marcgrabanski.com
* Project Page: http://marcgrabanski.com/article/clean-calendar
* Under the MIT License */
var popUpCal = {
selectedMonth: new Date().getMonth(),
// 0-11
selectedYear: new Date().getFullYear(),
// 4-digit year
selectedDay: new Date().getDate(),
calendarId: 'calendarDiv',
inputClass: 'calendarSelectDate',
init: function() {
var x = getElementsByClass(popUpCal.inputClass, document, 'input');
var y = document.getElementById(popUpCal.calendarId);
// set the calendar position based on the input position
for (var i = 0; i < x.length; i++) {
x[i].onfocus = function() {
popUpCal.selectedMonth = new Date().getMonth();
setPos(this, y);
// setPos(targetObj,moveObj)
y.style.display = 'block';
popUpCal.drawCalendar(this);
popUpCal.setupLinks(this);
}
}
},
drawCalendar: function(inputObj) {
var html = '';
html = '<a id="closeCalender"><img src="http://www.nzbmovieseeker.com/images/close.gif"></img></a>';
html += '<table cellpadding="0" cellspacing="0" id="linksTable"><tr>';
html += ' <td><a id="prevMonth"><b><< </b></a></td>';
html += '<td colspan="7" class="calendarHeader">' + getMonthName(popUpCal.selectedMonth) + ' ' + popUpCal.selectedYear + '</td>';
html += ' <td><a id="nextMonth"><b> >></b></a></td>';
html += '</tr></table>';
html += '<table id="calendar" cellpadding="0" cellspacing="0"><tr>';
html += '</tr><tr class="weekDaysTitleRow">';
var weekDays = new Array('D', 'S', 'T', 'Q', 'Q', 'S', 'S');
for (var j = 0; j < weekDays.length; j++) {
html += '<td>' + weekDays[j] + '</td>';
}
var daysInMonth = getDaysInMonth(popUpCal.selectedYear, popUpCal.selectedMonth);
var startDay = getFirstDayofMonth(popUpCal.selectedYear, popUpCal.selectedMonth);
var numRows = 0;
var printDate = 1;
if (startDay != 7) {
numRows = Math.ceil(((startDay + 1) + (daysInMonth)) / 7);
// calculate the number of rows to generate
}
// calculate number of days before calendar starts
if (startDay != 7) {
var noPrintDays = startDay + 1;
} else {
var noPrintDays = 0;
// if sunday print right away
}
var today = new Date().getDate();
var thisMonth = new Date().getMonth();
var thisYear = new Date().getFullYear();
// create calendar rows
for (var e = 0; e < numRows; e++) {
html += '<tr class="weekDaysRow">';
// create calendar days
for (var f = 0; f < 7; f++) {
if ((printDate == today)
&& (popUpCal.selectedYear == thisYear)
&& (popUpCal.selectedMonth == thisMonth)
&& (noPrintDays == 0)) {
html += '<td id="today" class="weekDaysCell">';
} else {
html += '<td class="weekDaysCell">';
}
if (noPrintDays == 0) {
if (printDate <= daysInMonth) {
html += '<a>' + printDate + '</a>';
}
printDate++;
}
html += '</td>';
if (noPrintDays > 0) noPrintDays--;
}
html += '</tr>';
}
html += '</table>';
html += '<!--[if lte IE 6.5]><iframe src="javascript:false;" id="calendar_cover"></iframe><![endif]-->';
// add calendar to element to calendar Div
var calendarDiv = document.getElementById(popUpCal.calendarId);
calendarDiv.innerHTML = html;
// close button link
document.getElementById('closeCalender').onclick = function() {
calendarDiv.style.display = 'none';
}
// setup next and previous links
document.getElementById('prevMonth').onclick = function() {
popUpCal.selectedMonth--;
if (popUpCal.selectedMonth < 0) {
popUpCal.selectedMonth = 11;
popUpCal.selectedYear--;
}
popUpCal.drawCalendar(inputObj);
popUpCal.setupLinks(inputObj);
}
document.getElementById('nextMonth').onclick = function() {
popUpCal.selectedMonth++;
if (popUpCal.selectedMonth > 11) {
popUpCal.selectedMonth = 0;
popUpCal.selectedYear++;
}
popUpCal.drawCalendar(inputObj);
popUpCal.setupLinks(inputObj);
}
},
// end drawCalendar function
setupLinks: function(inputObj) {
// set up link events on calendar table
var y = document.getElementById('calendar');
var x = y.getElementsByTagName('a');
for (var i = 0; i < x.length; i++) {
x[i].onmouseover = function() {
this.parentNode.className = 'weekDaysCellOver';
}
x[i].onmouseout = function() {
this.parentNode.className = 'weekDaysCell';
}
x[i].onclick = function() {
document.getElementById(popUpCal.calendarId).style.display = 'none';
popUpCal.selectedDay = this.innerHTML;
inputObj.value = formatDate(popUpCal.selectedDay, popUpCal.selectedMonth, popUpCal.selectedYear);
}
}
}
}
// Add calendar event that has wide browser support
if (typeof window.addEventListener != "undefined")
window.addEventListener("load", popUpCal.init, false);
else if (typeof window.attachEvent != "undefined")
window.attachEvent("onload", popUpCal.init);
else {
if (window.onload != null) {
var oldOnload = window.onload;
window.onload = function(e) {
oldOnload(e);
popUpCal.init();
};
}
else
window.onload = popUpCal.init;
}
/* Functions Dealing with Dates */
function formatDate(Day, Month, Year) {
Month++;
// adjust javascript month
if (Month < 10) Month = '0' + Month;
// add a zero if less than 10
if (Day < 10) Day = '0' + Day;
// add a zero if less than 10
var dateString = Year + '-' + Month + '-' + Day;
return dateString;
}
function getMonthName(month) {
var monthNames = new Array('Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro');
return monthNames[month];
}
function getDayName(day) {
var dayNames = new Array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')
return dayNames[day];
}
function getDaysInMonth(year, month) {
return 32 - new Date(year, month, 32).getDate();
}
function getFirstDayofMonth(year, month) {
var day;
day = new Date(year, month, 0).getDay();
return day;
}
/* Common Scripts */
function getElementsByClass(searchClass, node, tag) {
var classElements = new Array();
if (node == null) node = document;
if (tag == null) tag = '*';
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp("(^|\s)" + searchClass + "(\s|$)");
for (i = 0, j = 0; i < elsLen; i++) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
/* Position Functions */
function setPos(targetObj, moveObj) {
var coors = findPos(targetObj);
moveObj.style.position = 'absolute';
moveObj.style.top = coors[1] + 18 + 'px';
moveObj.style.left = coors[0] + 'px';
}
function findPos(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
curleft = obj.offsetLeft
curtop = obj.offsetTop
while (obj = obj.offsetParent) {
curleft += obj.offsetLeft
curtop += obj.offsetTop
}
}
return [curleft, curtop];
}
Or JSFDDILE example: http://jsfiddle.net/CJEC8/
Thanks
You can create a div that lies on top of the entire page, except the date picker itself. When you click the div, you close the datepicker (and remove the div, of course).
With a simple research I think i soulve your problem.
Paste this code before the method to close when you click in the button (before: // close button link
)
// Close when loses focus.
var divEls = document.getElementsByTagName("input");
var i = 0;
for(i=0;i<divEls.length;i++)
document.getElementById(divEls[i].id).onblur = function() {
calendarDiv.style.display = 'none';
}
Man, JsFiddle is so good.
Glad to help.
This is the answer to your question
var popUpCal = {
selectedMonth: new Date().getMonth(),
// 0-11
selectedYear: new Date().getFullYear(),
// 4-digit year
selectedDay: new Date().getDate(),
calendarId: 'calendarDiv',
inputClass: 'calendarSelectDate',
init: function() {
var x = getElementsByClass(popUpCal.inputClass, document, 'input');
var y = document.getElementById(popUpCal.calendarId);
// set the calendar position based on the input position
for (var i = 0; i < x.length; i++) {
x[i].onfocus=function() {
popUpCal.selectedMonth = new Date().getMonth();
setPos(this, y);
// setPos(targetObj,moveObj)
y.style.display = 'block';
popUpCal.drawCalendar(this);
popUpCal.setupLinks(this);
}
x[i].onblur=function(){
popUpCal.hideCalendar();
}
}
},
drawCalendar: function(inputObj){
var html = '';
html = '<a id="closeCalender"><img src="http://www.nzbmovieseeker.com/images/close.gif"></img></a>';
html += '<table cellpadding="0" cellspacing="0" id="linksTable"><tr>';
html += ' <td><a id="prevMonth"><b><< </b></a></td>';
html += '<td colspan="7" class="calendarHeader">' + getMonthName(popUpCal.selectedMonth) + ' ' + popUpCal.selectedYear + '</td>';
html += ' <td><a id="nextMonth"><b> >></b></a></td>';
html += '</tr></table>';
html += '<table id="calendar" cellpadding="0" cellspacing="0"><tr>';
html += '</tr><tr class="weekDaysTitleRow">';
var weekDays = new Array('D', 'S', 'T', 'Q', 'Q', 'S', 'S');
for (var j = 0; j < weekDays.length; j++) {
html += '<td>' + weekDays[j] + '</td>';
}
var daysInMonth = getDaysInMonth(popUpCal.selectedYear, popUpCal.selectedMonth);
var startDay = getFirstDayofMonth(popUpCal.selectedYear, popUpCal.selectedMonth);
var numRows = 0;
var printDate = 1;
if (startDay != 7) {
numRows = Math.ceil(((startDay + 1) + (daysInMonth)) / 7);
// calculate the number of rows to generate
}
// calculate number of days before calendar starts
if (startDay != 7) {
var noPrintDays = startDay + 1;
} else {
var noPrintDays = 0;
// if sunday print right away
}
var today = new Date().getDate();
var thisMonth = new Date().getMonth();
var thisYear = new Date().getFullYear();
// create calendar rows
for (var e = 0; e < numRows; e++) {
html += '<tr class="weekDaysRow">';
// create calendar days
for (var f = 0; f < 7; f++) {
if ((printDate == today) && (popUpCal.selectedYear == thisYear) && (popUpCal.selectedMonth == thisMonth) && (noPrintDays == 0)) {
html += '<td id="today" class="weekDaysCell">';
} else {
html += '<td class="weekDaysCell">';
}
if (noPrintDays == 0) {
if (printDate <= daysInMonth) {
html += '<a>' + printDate + '</a>';
}
printDate++;
}
html += '</td>';
if (noPrintDays > 0) noPrintDays--;
}
html += '</tr>';
}
html += '</table>';
html += '<!--[if lte IE 6.5]><iframe src="javascript:false;" id="calendar_cover"></iframe><![endif]-->';
// add calendar to element to calendar Div
var calendarDiv = document.getElementById(popUpCal.calendarId);
calendarDiv.innerHTML = html;
// close button link
document.getElementById('closeCalender').onclick = function() {
calendarDiv.style.display = 'none';
}
// setup next and previous links
document.getElementById('prevMonth').onclick = function() {
popUpCal.selectedMonth--;
if (popUpCal.selectedMonth < 0) {
popUpCal.selectedMonth = 11;
popUpCal.selectedYear--;
}
popUpCal.drawCalendar(inputObj);
popUpCal.setupLinks(inputObj);
}
document.getElementById('nextMonth').onclick = function() {
popUpCal.selectedMonth++;
if (popUpCal.selectedMonth > 11) {
popUpCal.selectedMonth = 0;
popUpCal.selectedYear++;
}
popUpCal.drawCalendar(inputObj);
popUpCal.setupLinks(inputObj);
}
},
hideCalendar:function(){
var calendarDiv=document.getElementById(popUpCal.calendarId);
calendarDiv.style.display = 'none';
},
// end drawCalendar function
setupLinks: function(inputObj) {
// set up link events on calendar table
var y = document.getElementById('calendar');
var x = y.getElementsByTagName('a');
for (var i = 0; i < x.length; i++) {
x[i].onmouseover = function() {
this.parentNode.className = 'weekDaysCellOver';
}
x[i].onmouseout = function() {
this.parentNode.className = 'weekDaysCell';
}
x[i].onclick = function() {
document.getElementById(popUpCal.calendarId).style.display = 'none';
popUpCal.selectedDay = this.innerHTML;
inputObj.value = formatDate(popUpCal.selectedDay, popUpCal.selectedMonth, popUpCal.selectedYear);
}
}
}
}
// Add calendar event that has wide browser support
if (typeof window.addEventListener != "undefined") window.addEventListener("load", popUpCal.init, false);
else if (typeof window.attachEvent != "undefined") window.attachEvent("onload", popUpCal.init);
else {
if (window.onload != null) {
var oldOnload = window.onload;
window.onload = function(e) {
oldOnload(e);
popUpCal.init();
};
}
else window.onload = popUpCal.init;
}
/* Functions Dealing with Dates */
function formatDate(Day, Month, Year) {
Month++;
// adjust javascript month
if (Month < 10) Month = '0' + Month;
// add a zero if less than 10
if (Day < 10) Day = '0' + Day;
// add a zero if less than 10
var dateString = Year + '-' + Month + '-' + Day;
return dateString;
}
function getMonthName(month) {
var monthNames = new Array('Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro');
return monthNames[month];
}
function getDayName(day) {
var dayNames = new Array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')
return dayNames[day];
}
function getDaysInMonth(year, month) {
return 32 - new Date(year, month, 32).getDate();
}
function getFirstDayofMonth(year, month) {
var day;
day = new Date(year, month, 0).getDay();
return day;
}
/* Common Scripts */
function getElementsByClass(searchClass, node, tag) {
var classElements = new Array();
if (node == null) node = document;
if (tag == null) tag = '*';
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp("(^|\s)" + searchClass + "(\s|$)");
for (i = 0, j = 0; i < elsLen; i++) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
/* Position Functions */
function setPos(targetObj, moveObj) {
var coors = findPos(targetObj);
moveObj.style.position = 'absolute';
moveObj.style.top = coors[1] + 18 + 'px';
moveObj.style.left = coors[0] + 'px';
}
function findPos(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
curleft = obj.offsetLeft
curtop = obj.offsetTop
while (obj = obj.offsetParent) {
curleft += obj.offsetLeft
curtop += obj.offsetTop
}
}
return [curleft, curtop];
}
I have added the
x[i].onblur=function(){
popUpCal.hideCalendar();
}
In the init function
And a new function hideCalendar after the //end drawCalendar function
// end drawCalendar function
hideCalendar:function(){
var calendarDiv=document.getElementById(popUpCal.calendarId);
calendarDiv.style.display = 'none';
},
Please keep in mind, that this is a simple fix. I would recommend using another lib for this. You can try jQuery or one of the many other datepickers out there..
--Cheers, Ex
Something like this:
html
<div id="closeCalendar"></div>
css
#closeCalendar {display:none;position:fixed; top:0; left:0; height:100%; width:100%; z-index:100;}
#calendarDiv {z-index: 200;}
js
document.getElementById('closeCalendar').onclick = function() {
document.getElementById('calendarDiv').style.display = 'none';
document.getElementById('closeCalendar').style.display = 'none';
}
...
init:
...
document.getElementById('closeCalendar').style.display = 'block';
...

Categories

Resources