Odometer alphanumeric value - javascript

I'm using "odometer" and i want to display its value as AB1234, this could be a random value. I tried to change its format but it shows an error if I made changes in format.
Please help me out in this. link of file is:
http://github.hubspot.com/odometer/odometer.js
Please see the code below:
How can I display value on odometer like AB1234??
(function() {
var COUNT_FRAMERATE, COUNT_MS_PER_FRAME, DIGIT_FORMAT, DIGIT_HTML, DIGIT_SPEEDBOOST, DURATION, FORMAT_MARK_HTML, FORMAT_PARSER, FRAMERATE, FRAMES_PER_VALUE, MS_PER_FRAME, MutationObserver, Odometer, RIBBON_HTML, TRANSITION_END_EVENTS, TRANSITION_SUPPORT, VALUE_HTML, addClass, createFromHTML, fractionalPart, now, removeClass, requestAnimationFrame, round, transitionCheckStyles, trigger, truncate, wrapJQuery, _jQueryWrapped, _old, _ref, _ref1,
__slice = [].slice;
VALUE_HTML = '<span class="odometer-value"></span>';
RIBBON_HTML = '<span class="odometer-ribbon"><span class="odometer-ribbon-inner">' + VALUE_HTML + '</span></span>';
DIGIT_HTML = '<span class="odometer-digit"><span class="odometer-digit-spacer">8</span><span class="odometer-digit-inner">' + RIBBON_HTML + '</span></span>';
FORMAT_MARK_HTML = '<span class="odometer-formatting-mark"></span>';
DIGIT_FORMAT = '(ddd).dd';
FORMAT_PARSER = /^\(?([^)]*)\)?(?:(.)(d+))?$/;
FRAMERATE = 30;
DURATION = 3000;
COUNT_FRAMERATE = 20;
FRAMES_PER_VALUE = 2;
DIGIT_SPEEDBOOST = .5;
MS_PER_FRAME = 1000 / FRAMERATE;
COUNT_MS_PER_FRAME = 1000 / COUNT_FRAMERATE;
TRANSITION_END_EVENTS = 'transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd';
transitionCheckStyles = document.createElement('div').style;
TRANSITION_SUPPORT = (transitionCheckStyles.transition != null) || (transitionCheckStyles.webkitTransition != null) || (transitionCheckStyles.mozTransition != null) || (transitionCheckStyles.oTransition != null);
requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
createFromHTML = function(html) {
var el;
el = document.createElement('div');
el.innerHTML = html;
return el.children[0];
};
removeClass = function(el, name) {
return el.className = el.className.replace(new RegExp("(^| )" + (name.split(' ').join('|')) + "( |$)", 'gi'), ' ');
};
addClass = function(el, name) {
removeClass(el, name);
return el.className += " " + name;
};
trigger = function(el, name) {
var evt;
if (document.createEvent != null) {
evt = document.createEvent('HTMLEvents');
evt.initEvent(name, true, true);
return el.dispatchEvent(evt);
}
};
now = function() {
var _ref, _ref1;
return (_ref = (_ref1 = window.performance) != null ? typeof _ref1.now === "function" ? _ref1.now() : void 0 : void 0) != null ? _ref : +(new Date);
};
round = function(val, precision) {
if (precision == null) {
precision = 0;
}
if (!precision) {
return Math.round(val);
}
val *= Math.pow(10, precision);
val += 0.5;
val = Math.floor(val);
return val /= Math.pow(10, precision);
};
truncate = function(val) {
if (val < 0) {
return Math.ceil(val);
} else {
return Math.floor(val);
}
};
fractionalPart = function(val) {
return val - round(val);
};
_jQueryWrapped = false;
(wrapJQuery = function() {
var property, _i, _len, _ref, _results;
if (_jQueryWrapped) {
return;
}
if (window.jQuery != null) {
_jQueryWrapped = true;
_ref = ['html', 'text'];
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
property = _ref[_i];
_results.push((function(property) {
var old;
old = window.jQuery.fn[property];
return window.jQuery.fn[property] = function(val) {
var _ref1;
if ((val == null) || (((_ref1 = this[0]) != null ? _ref1.odometer : void 0) == null)) {
return old.apply(this, arguments);
}
return this[0].odometer.update(val);
};
})(property));
}
return _results;
}
})();
setTimeout(wrapJQuery, 0);
Odometer = (function() {
function Odometer(options) {
var e, k, property, v, _base, _i, _len, _ref, _ref1, _ref2,
_this = this;
this.options = options;
this.el = this.options.el;
if (this.el.odometer != null) {
return this.el.odometer;
}
this.el.odometer = this;
_ref = Odometer.options;
for (k in _ref) {
v = _ref[k];
if (this.options[k] == null) {
this.options[k] = v;
}
}
if ((_base = this.options).duration == null) {
_base.duration = DURATION;
}
this.MAX_VALUES = ((this.options.duration / MS_PER_FRAME) / FRAMES_PER_VALUE) | 0;
this.resetFormat();
this.value = this.cleanValue((_ref1 = this.options.value) != null ? _ref1 : '');
this.renderInside();
this.render();
try {
_ref2 = ['innerHTML', 'innerText', 'textContent'];
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
property = _ref2[_i];
if (this.el[property] != null) {
(function(property) {
return Object.defineProperty(_this.el, property, {
get: function() {
var _ref3;
if (property === 'innerHTML') {
return _this.inside.outerHTML;
} else {
return (_ref3 = _this.inside.innerText) != null ? _ref3 : _this.inside.textContent;
}
},
set: function(val) {
return _this.update(val);
}
});
})(property);
}
}
} catch (_error) {
e = _error;
this.watchForMutations();
}
this;
}
Odometer.prototype.renderInside = function() {
this.inside = document.createElement('div');
this.inside.className = 'odometer-inside';
this.el.innerHTML = '';
return this.el.appendChild(this.inside);
};
Odometer.prototype.watchForMutations = function() {
var e,
_this = this;
if (MutationObserver == null) {
return;
}
try {
if (this.observer == null) {
this.observer = new MutationObserver(function(mutations) {
var newVal;
newVal = _this.el.innerText;
_this.renderInside();
_this.render(_this.value);
return _this.update(newVal);
});
}
this.watchMutations = true;
return this.startWatchingMutations();
} catch (_error) {
e = _error;
}
};
Odometer.prototype.startWatchingMutations = function() {
if (this.watchMutations) {
return this.observer.observe(this.el, {
childList: true
});
}
};
Odometer.prototype.stopWatchingMutations = function() {
var _ref;
return (_ref = this.observer) != null ? _ref.disconnect() : void 0;
};
Odometer.prototype.cleanValue = function(val) {
var _ref;
if (typeof val === 'string') {
val = val.replace((_ref = this.format.radix) != null ? _ref : '.', '<radix>');
val = val.replace(/[.,]/g, '');
val = val.replace('<radix>', '.');
val = parseFloat(val, 10) || 0;
}
return round(val, this.format.precision);
};
Odometer.prototype.bindTransitionEnd = function() {
var event, renderEnqueued, _i, _len, _ref, _results,
_this = this;
if (this.transitionEndBound) {
return;
}
this.transitionEndBound = true;
renderEnqueued = false;
_ref = TRANSITION_END_EVENTS.split(' ');
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
event = _ref[_i];
_results.push(this.el.addEventListener(event, function() {
if (renderEnqueued) {
return true;
}
renderEnqueued = true;
setTimeout(function() {
_this.render();
renderEnqueued = false;
return trigger(_this.el, 'odometerdone');
}, 0);
return true;
}, false));
}
return _results;
};
Odometer.prototype.resetFormat = function() {
var format, fractional, parsed, precision, radix, repeating, _ref, _ref1;
format = (_ref = this.options.format) != null ? _ref : DIGIT_FORMAT;
format || (format = 'd');
parsed = FORMAT_PARSER.exec(format);
if (!parsed) {
throw new Error("Odometer: Unparsable digit format");
}
_ref1 = parsed.slice(1, 4), repeating = _ref1[0], radix = _ref1[1], fractional = _ref1[2];
precision = (fractional != null ? fractional.length : void 0) || 0;
return this.format = {
repeating: repeating,
radix: radix,
precision: precision
};
};
Odometer.prototype.render = function(value) {
var classes, cls, match, newClasses, theme, _i, _len;
if (value == null) {
value = this.value;
}
this.stopWatchingMutations();
this.resetFormat();
this.inside.innerHTML = '';
theme = this.options.theme;
classes = this.el.className.split(' ');
newClasses = [];
for (_i = 0, _len = classes.length; _i < _len; _i++) {
cls = classes[_i];
if (!cls.length) {
continue;
}
if (match = /^odometer-theme-(.+)$/.exec(cls)) {
theme = match[1];
continue;
}
if (/^odometer(-|$)/.test(cls)) {
continue;
}
newClasses.push(cls);
}
newClasses.push('odometer');
if (!TRANSITION_SUPPORT) {
newClasses.push('odometer-no-transitions');
}
if (theme) {
newClasses.push("odometer-theme-" + theme);
} else {
newClasses.push("odometer-auto-theme");
}
this.el.className = newClasses.join(' ');
this.ribbons = {};
this.formatDigits(value);
return this.startWatchingMutations();
};
Odometer.prototype.formatDigits = function(value) {
var digit, valueDigit, valueString, wholePart, _i, _j, _len, _len1, _ref, _ref1;
this.digits = [];
if (this.options.formatFunction) {
valueString = this.options.formatFunction(value);
_ref = valueString.split('').reverse();
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
valueDigit = _ref[_i];
if (valueDigit.match(/0-9/)) {
digit = this.renderDigit();
digit.querySelector('.odometer-value').innerHTML = valueDigit;
this.digits.push(digit);
this.insertDigit(digit);
} else {
this.addSpacer(valueDigit);
}
}
} else {
wholePart = !this.format.precision || !fractionalPart(value) || false;
_ref1 = value.toString().split('').reverse();
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
digit = _ref1[_j];
if (digit === '.') {
wholePart = true;
}
this.addDigit(digit, wholePart);
}
}
};
Odometer.prototype.update = function(newValue) {
var diff,
_this = this;
newValue = this.cleanValue(newValue);
if (!(diff = newValue - this.value)) {
return;
}
removeClass(this.el, 'odometer-animating-up odometer-animating-down odometer-animating');
if (diff > 0) {
addClass(this.el, 'odometer-animating-up');
} else {
addClass(this.el, 'odometer-animating-down');
}
this.stopWatchingMutations();
this.animate(newValue);
this.startWatchingMutations();
setTimeout(function() {
_this.el.offsetHeight;
return addClass(_this.el, 'odometer-animating');
}, 0);
return this.value = newValue;
};
Odometer.prototype.renderDigit = function() {
return createFromHTML(DIGIT_HTML);
};
Odometer.prototype.insertDigit = function(digit, before) {
if (before != null) {
return this.inside.insertBefore(digit, before);
} else if (!this.inside.children.length) {
return this.inside.appendChild(digit);
} else {
return this.inside.insertBefore(digit, this.inside.children[0]);
}
};
Odometer.prototype.addSpacer = function(chr, before, extraClasses) {
var spacer;
spacer = createFromHTML(FORMAT_MARK_HTML);
spacer.innerHTML = chr;
if (extraClasses) {
addClass(spacer, extraClasses);
}
return this.insertDigit(spacer, before);
};
Odometer.prototype.addDigit = function(value, repeating) {
var chr, digit, resetted, _ref;
if (repeating == null) {
repeating = true;
}
if (value === '-') {
return this.addSpacer(value, null, 'odometer-negation-mark');
}
if (value === '.') {
return this.addSpacer((_ref = this.format.radix) != null ? _ref : '.', null, 'odometer-radix-mark');
}
if (repeating) {
resetted = false;
while (true) {
if (!this.format.repeating.length) {
if (resetted) {
throw new Error("Bad odometer format without digits");
}
this.resetFormat();
resetted = true;
}
chr = this.format.repeating[this.format.repeating.length - 1];
this.format.repeating = this.format.repeating.substring(0, this.format.repeating.length - 1);
if (chr === 'd') {
break;
}
this.addSpacer(chr);
}
}
digit = this.renderDigit();
digit.querySelector('.odometer-value').innerHTML = value;
this.digits.push(digit);
return this.insertDigit(digit);
};
Odometer.prototype.animate = function(newValue) {
if (!TRANSITION_SUPPORT || this.options.animation === 'count') {
return this.animateCount(newValue);
} else {
return this.animateSlide(newValue);
}
};
Odometer.prototype.animateCount = function(newValue) {
var cur, diff, last, start, tick,
_this = this;
if (!(diff = +newValue - this.value)) {
return;
}
start = last = now();
cur = this.value;
return (tick = function() {
var delta, dist, fraction;
if ((now() - start) > _this.options.duration) {
_this.value = newValue;
_this.render();
trigger(_this.el, 'odometerdone');
return;
}
delta = now() - last;
if (delta > COUNT_MS_PER_FRAME) {
last = now();
fraction = delta / _this.options.duration;
dist = diff * fraction;
cur += dist;
_this.render(Math.round(cur));
}
if (requestAnimationFrame != null) {
return requestAnimationFrame(tick);
} else {
return setTimeout(tick, COUNT_MS_PER_FRAME);
}
})();
};
Odometer.prototype.getDigitCount = function() {
var i, max, value, values, _i, _len;
values = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
for (i = _i = 0, _len = values.length; _i < _len; i = ++_i) {
value = values[i];
values[i] = Math.abs(value);
}
max = Math.max.apply(Math, values);
return Math.ceil(Math.log(max + 1) / Math.log(10));
};
Odometer.prototype.getFractionalDigitCount = function() {
var i, parser, parts, value, values, _i, _len;
values = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
parser = /^\-?\d*\.(\d*?)0*$/;
for (i = _i = 0, _len = values.length; _i < _len; i = ++_i) {
value = values[i];
values[i] = value.toString();
parts = parser.exec(values[i]);
if (parts == null) {
values[i] = 0;
} else {
values[i] = parts[1].length;
}
}
return Math.max.apply(Math, values);
};
Odometer.prototype.resetDigits = function() {
this.digits = [];
this.ribbons = [];
this.inside.innerHTML = '';
return this.resetFormat();
};
Odometer.prototype.animateSlide = function(newValue) {
var boosted, cur, diff, digitCount, digits, dist, end, fractionalCount, frame, frames, i, incr, j, mark, numEl, oldValue, start, _base, _i, _j, _k, _l, _len, _len1, _len2, _m, _ref, _results;
oldValue = this.value;
fractionalCount = this.getFractionalDigitCount(oldValue, newValue);
if (fractionalCount) {
newValue = newValue * Math.pow(10, fractionalCount);
oldValue = oldValue * Math.pow(10, fractionalCount);
}
if (!(diff = newValue - oldValue)) {
return;
}
this.bindTransitionEnd();
digitCount = this.getDigitCount(oldValue, newValue);
digits = [];
boosted = 0;
for (i = _i = 0; 0 <= digitCount ? _i < digitCount : _i > digitCount; i = 0 <= digitCount ? ++_i : --_i) {
start = truncate(oldValue / Math.pow(10, digitCount - i - 1));
end = truncate(newValue / Math.pow(10, digitCount - i - 1));
dist = end - start;
if (Math.abs(dist) > this.MAX_VALUES) {
frames = [];
incr = dist / (this.MAX_VALUES + this.MAX_VALUES * boosted * DIGIT_SPEEDBOOST);
cur = start;
while ((dist > 0 && cur < end) || (dist < 0 && cur > end)) {
frames.push(Math.round(cur));
cur += incr;
}
if (frames[frames.length - 1] !== end) {
frames.push(end);
}
boosted++;
} else {
frames = (function() {
_results = [];
for (var _j = start; start <= end ? _j <= end : _j >= end; start <= end ? _j++ : _j--){ _results.push(_j); }
return _results;
}).apply(this);
}
for (i = _k = 0, _len = frames.length; _k < _len; i = ++_k) {
frame = frames[i];
frames[i] = Math.abs(frame % 10);
}
digits.push(frames);
}
this.resetDigits();
_ref = digits.reverse();
for (i = _l = 0, _len1 = _ref.length; _l < _len1; i = ++_l) {
frames = _ref[i];
if (!this.digits[i]) {
this.addDigit(' ', i >= fractionalCount);
}
if ((_base = this.ribbons)[i] == null) {
_base[i] = this.digits[i].querySelector('.odometer-ribbon-inner');
}
this.ribbons[i].innerHTML = '';
if (diff < 0) {
frames = frames.reverse();
}
for (j = _m = 0, _len2 = frames.length; _m < _len2; j = ++_m) {
frame = frames[j];
numEl = document.createElement('div');
numEl.className = 'odometer-value';
numEl.innerHTML = frame;
this.ribbons[i].appendChild(numEl);
if (j === frames.length - 1) {
addClass(numEl, 'odometer-last-value');
}
if (j === 0) {
addClass(numEl, 'odometer-first-value');
}
}
}
if (start < 0) {
this.addDigit('-');
}
mark = this.inside.querySelector('.odometer-radix-mark');
if (mark != null) {
mark.parent.removeChild(mark);
}
if (fractionalCount) {
return this.addSpacer(this.format.radix, this.digits[fractionalCount - 1], 'odometer-radix-mark');
}
};
return Odometer;
})();
Odometer.options = (_ref = window.odometerOptions) != null ? _ref : {};
setTimeout(function() {
var k, v, _base, _ref1, _results;
if (window.odometerOptions) {
_ref1 = window.odometerOptions;
_results = [];
for (k in _ref1) {
v = _ref1[k];
_results.push((_base = Odometer.options)[k] != null ? (_base = Odometer.options)[k] : _base[k] = v);
}
return _results;
}
}, 0);
Odometer.init = function() {
var el, elements, _i, _len, _ref1, _results;
if (document.querySelectorAll == null) {
return;
}
elements = document.querySelectorAll(Odometer.options.selector || '.odometer');
_results = [];
for (_i = 0, _len = elements.length; _i < _len; _i++) {
el = elements[_i];
_results.push(el.odometer = new Odometer({
el: el,
value: (_ref1 = el.innerText) != null ? _ref1 : el.textContent
}));
}
return _results;
};
if ((((_ref1 = document.documentElement) != null ? _ref1.doScroll : void 0) != null) && (document.createEventObject != null)) {
_old = document.onreadystatechange;
document.onreadystatechange = function() {
if (document.readyState === 'complete' && Odometer.options.auto !== false) {
Odometer.init();
}
return _old != null ? _old.apply(this, arguments) : void 0;
};
} else {
document.addEventListener('DOMContentLoaded', function() {
if (Odometer.options.auto !== false) {
return Odometer.init();
}
}, false);
}
if (typeof define === 'function' && define.amd) {
define([], function() {
return Odometer;
});
} else if (typeof exports !== "undefined" && exports !== null) {
module.exports = Odometer;
} else {
window.Odometer = Odometer;
}
}).call(this);

Related

How to style a cell's children when exporting an html table to XLSX

How do you style cell child elements in the export process?
Given a foo table like this:
<table id="myTableName">
<thead id="myTableNameHdr"><tr><th style="background-color:navy;color:white;">Test<th></tr></thead>
<tbody id="myTableNameBod"><tr><td>
Choose
<span style="color:red">RED </span>
or
<span style="color:blue">BLUE </span>
colors...
<td></tr></tbody>
</table>
How can I render the red and blue text in the cell in a way that translates for excel. Using inline styles works well for the cell level styles as i have it in my foo header row. However, the inner text styles are dropped. I realize this could be a by product of getting the text attribute vs iterating the children in the lib I'm using. Is there an alternative?
I am using a js that I inherited and I do not have the non-minified version :( I'm hoping someone knows who's it is. Maybe someone might recognize it.
Portion of formatted min.js code: (did not include all of it because >35K lines total)
if (!Object.keys) {
Object.keys = (function () {
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !({
toString: null
})
.propertyIsEnumerable("toString"),
dontEnums = ["toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "constructor"],
dontEnumsLength = dontEnums.length;
return function (obj) {
if (typeof obj !== "object" && typeof obj !== "function" || obj === null) {
throw new TypeError("Object.keys called on non-object");
}
var result = [];
for (var prop in obj) {
if (hasOwnProperty.call(obj, prop)) {
result.push(prop);
}
}
if (hasDontEnumBug) {
for (var i = 0; i < dontEnumsLength; i++) {
if (hasOwnProperty.call(obj, dontEnums[i])) {
result.push(dontEnums[i]);
}
}
}
return result;
};
})();
}
if (!Array.prototype.filter) {
Array.prototype.filter = function (fun) {
if (this == null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun != "function") {
throw new TypeError();
}
var res = [];
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i];
if (fun.call(thisp, val, i, t)) {
res.push(val);
}
}
}
return res;
};
}
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, "");
};
}
if (!Array.prototype.forEach) {
Array.prototype.forEach = function (fun) {
if (this === void 0 || this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== "function") {
throw new TypeError();
}
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++) {
if (i in t) {
fun.call(thisArg, t[i], i, t);
}
}
};
}
if (!Array.prototype.map) {
Array.prototype.map = function (callback, thisArg) {
var T, A, k;
if (this == null) {
throw new TypeError(" this is null or not defined");
}
var O = Object(this);
var len = O.length >>> 0;
if (typeof callback !== "function") {
throw new TypeError(callback + " is not a function");
}
if (thisArg) {
T = thisArg;
}
A = new Array(len);
k = 0;
while (k < len) {
var kValue, mappedValue;
if (k in O) {
kValue = O[k];
mappedValue = callback.call(T, kValue, k, O);
A[k] = mappedValue;
}
k++;
}
return A;
};
}
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement, fromIndex) {
if (this === undefined || this === null) {
throw new TypeError('"this" is null or not defined');
}
var length = this.length >>> 0;
fromIndex = +fromIndex || 0;
if (Math.abs(fromIndex) === Infinity) {
fromIndex = 0;
}
if (fromIndex < 0) {
fromIndex += length;
if (fromIndex < 0) {
fromIndex = 0;
}
}
for (; fromIndex < length; fromIndex++) {
if (this[fromIndex] === searchElement) {
return fromIndex;
}
}
return -1;
};
}
if (!Array.isArray) {
Array.isArray = function (obj) {
return Object.prototype.toString.call(obj) === "[object Array]";
};
}
"use strict";
if (typeof ArrayBuffer !== "undefined" && !ArrayBuffer.prototype.slice) {
ArrayBuffer.prototype.slice = function (begin, end) {
begin = (begin | 0) || 0;
var num = this.byteLength;
end = end === (void 0) ? num : (end | 0);
if (begin < 0) {
begin += num;
Deeper snippet same file:
var HTML_ = (function () {
function html_to_sheet(str, _opts) {
var opts = _opts || {};
if (DENSE != null && opts.dense == null) {
opts.dense = DENSE;
}
var ws = opts.dense ? ([]) : ({});
var i = str.indexOf("<table"),
j = str.indexOf("</table");
if (i == -1 || j == -1) {
throw new Error("Invalid HTML: missing <table> / </table> pair");
}
var rows = str.slice(i, j)
.split(/(:?<tr[^>]*>)/);
var R = -1,
C = 0,
RS = 0,
CS = 0;
var range = {
s: {
r: 10000000,
c: 10000000
},
e: {
r: 0,
c: 0
}
};
var merges = [],
midx = 0;
for (i = 0; i < rows.length; ++i) {
var row = rows[i].trim();
if (row.substr(0, 3) == "<tr") {
++R;
C = 0;
continue;
}
if (row.substr(0, 3) != "<td") {
continue;
}
var cells = row.split("</td>");
for (j = 0; j < cells.length; ++j) {
var cell = cells[j].trim();
if (cell.substr(0, 3) != "<td") {
continue;
}
var m = cell,
cc = 0;
while (m.charAt(0) == "<" && (cc = m.indexOf(">")) > -1) {
m = m.slice(cc + 1);
}
while (m.indexOf(">") > -1) {
m = m.slice(0, m.lastIndexOf("<"));
}
var tag = parsexmltag(cell.slice(0, cell.indexOf(">")));
CS = tag.colspan ? +tag.colspan : 1;
if ((RS = +tag.rowspan) > 0 || CS > 1) {
merges.push({
s: {
r: R,
c: C
},
e: {
r: R + (RS || 1) - 1,
c: C + CS - 1
}
});
}
if (!m.length) {
C += CS;
continue;
}
m = unescapexml(m)
.replace(/[\r\n]/g, "");
if (range.s.r > R) {
range.s.r = R;
}
if (range.e.r < R) {
range.e.r = R;
}
if (range.s.c > C) {
range.s.c = C;
}
if (range.e.c < C) {
range.e.c = C;
}
if (opts.dense) {
if (!ws[R]) {
ws[R] = [];
}
if (Number(m) == Number(m)) {
ws[R][C] = {
t: "n",
v: +m
};
} else {
ws[R][C] = {
t: "s",
v: m
};
}
} else {
var coord = encode_cell({
r: R,
c: C
});
if (Number(m) == Number(m)) {
ws[coord] = {
t: "n",
v: +m
};
} else {
ws[coord] = {
t: "s",
v: m
};
}
}
C += CS;
}
}
ws["!ref"] = encode_range(range);
return ws;
}
The answer is it can be done as long as you pay for the pro version.

How to convert from Path to XPath, given a browser event

On a MouseEvent instance, we have a property called path, it might look like this:
Does anybody know if there is a reliable way to translate this path array into an XPath? I assume that this path data is the best data to start from? Is there a library I can use to do the conversion?
This library looks promising, but it doesn't use the path property of an event: https://github.com/johannhof/xpath-dom
There's not a unique XPath to a node, so you'll have to decide what's the most appropriate way of constructing a path. Use IDs where available? Numeral position in the document? Position relative to other elements?
See getPathTo() in this answer for one possible approach.
PS: Taken from Javascript get XPath of a node
Another option is to use SelectorGadget from below link
https://dv0akt2986vzh.cloudfront.net/unstable/lib/selectorgadget.js
The actual code for the DOM path is at
https://dv0akt2986vzh.cloudfront.net/stable/lib/dom.js
Usage: on http://google.com
elem = document.getElementById("q")
predict = new DomPredictionHelper()
predict.pathOf(elem)
// gives "body.default-theme.des-mat:nth-child(2) div#_Alw:nth-child(4) form#f:nth-child(2) div#fkbx:nth-child(2) input#q:nth-child(2)"
predict.predictCss([elem],[])
// gives "#q"
CODE if link goes down
// Copyright (c) 2008, 2009 Andrew Cantino
// Copyright (c) 2008, 2009 Kyle Maxwell
function DomPredictionHelper() {};
DomPredictionHelper.prototype = new Object();
DomPredictionHelper.prototype.recursiveNodes = function(e){
var n;
if(e.nodeName && e.parentNode && e != document.body) {
n = this.recursiveNodes(e.parentNode);
} else {
n = new Array();
}
n.push(e);
return n;
};
DomPredictionHelper.prototype.escapeCssNames = function(name) {
if (name) {
try {
return name.replace(/\s*sg_\w+\s*/g, '').replace(/\\/g, '\\\\').
replace(/\./g, '\\.').replace(/#/g, '\\#').replace(/\>/g, '\\>').replace(/\,/g, '\\,').replace(/\:/g, '\\:');
} catch(e) {
console.log('---');
console.log("exception in escapeCssNames");
console.log(name);
console.log('---');
return '';
}
} else {
return '';
}
};
DomPredictionHelper.prototype.childElemNumber = function(elem) {
var count = 0;
while (elem.previousSibling && (elem = elem.previousSibling)) {
if (elem.nodeType == 1) count++;
}
return count;
};
DomPredictionHelper.prototype.pathOf = function(elem){
var nodes = this.recursiveNodes(elem);
var self = this;
var path = "";
for(var i = 0; i < nodes.length; i++) {
var e = nodes[i];
if (e) {
path += e.nodeName.toLowerCase();
var escaped = e.id && self.escapeCssNames(new String(e.id));
if(escaped && escaped.length > 0) path += '#' + escaped;
if(e.className) {
jQuery.each(e.className.split(/ /), function() {
var escaped = self.escapeCssNames(this);
if (this && escaped.length > 0) {
path += '.' + escaped;
}
});
}
path += ':nth-child(' + (self.childElemNumber(e) + 1) + ')';
path += ' '
}
}
if (path.charAt(path.length - 1) == ' ') path = path.substring(0, path.length - 1);
return path;
};
DomPredictionHelper.prototype.commonCss = function(array) {
try {
var dmp = new diff_match_patch();
} catch(e) {
throw "Please include the diff_match_patch library.";
}
if (typeof array == 'undefined' || array.length == 0) return '';
var existing_tokens = {};
var encoded_css_array = this.encodeCssForDiff(array, existing_tokens);
var collective_common = encoded_css_array.pop();
jQuery.each(encoded_css_array, function(e) {
var diff = dmp.diff_main(collective_common, this);
collective_common = '';
jQuery.each(diff, function() {
if (this[0] == 0) collective_common += this[1];
});
});
return this.decodeCss(collective_common, existing_tokens);
};
DomPredictionHelper.prototype.tokenizeCss = function(css_string) {
var skip = false;
var word = '';
var tokens = [];
var css_string = css_string.replace(/,/, ' , ').replace(/\s+/g, ' ');
var length = css_string.length;
var c = '';
for (var i = 0; i < length; i++){
c = css_string[i];
if (skip) {
skip = false;
} else if (c == '\\') {
skip = true;
} else if (c == '.' || c == ' ' || c == '#' || c == '>' || c == ':' || c == ',') {
if (word.length > 0) tokens.push(word);
word = '';
}
word += c;
if (c == ' ' || c == ',') {
tokens.push(word);
word = '';
}
}
if (word.length > 0) tokens.push(word);
return tokens;
};
DomPredictionHelper.prototype.decodeCss = function(string, existing_tokens) {
var inverted = this.invertObject(existing_tokens);
var out = '';
jQuery.each(string.split(''), function() {
out += inverted[this];
});
return this.cleanCss(out);
};
// Encode css paths for diff using unicode codepoints to allow for a large number of tokens.
DomPredictionHelper.prototype.encodeCssForDiff = function(strings, existing_tokens) {
var codepoint = 50;
var self = this;
var strings_out = [];
jQuery.each(strings, function() {
var out = new String();
jQuery.each(self.tokenizeCss(this), function() {
if (!existing_tokens[this]) {
existing_tokens[this] = String.fromCharCode(codepoint++);
}
out += existing_tokens[this];
});
strings_out.push(out);
});
return strings_out;
};
DomPredictionHelper.prototype.simplifyCss = function(css, selected_paths, rejected_paths) {
var self = this;
var parts = self.tokenizeCss(css);
var best_so_far = "";
if (self.selectorGets('all', selected_paths, css) && self.selectorGets('none', rejected_paths, css)) best_so_far = css;
for (var pass = 0; pass < 4; pass++) {
for (var part = 0; part < parts.length; part++) {
var first = parts[part].substring(0,1);
if (self.wouldLeaveFreeFloatingNthChild(parts, part)) continue;
if ((pass == 0 && first == ':') || // :nth-child
(pass == 1 && first != ':' && first != '.' && first != '#' && first != ' ') || // elem, etc.
(pass == 2 && first == '.') || // classes
(pass == 3 && first == '#')) // ids
{
var tmp = parts[part];
parts[part] = '';
var selector = self.cleanCss(parts.join(''));
if (selector == '') {
parts[part] = tmp;
continue;
}
if (self.selectorGets('all', selected_paths, selector) && self.selectorGets('none', rejected_paths, selector)) {
best_so_far = selector;
} else {
parts[part] = tmp;
}
}
}
}
return self.cleanCss(best_so_far);
};
DomPredictionHelper.prototype.wouldLeaveFreeFloatingNthChild = function(parts, part) {
return (((part - 1 >= 0 && parts[part - 1].substring(0, 1) == ':') &&
(part - 2 < 0 || parts[part - 2] == ' ') &&
(part + 1 >= parts.length || parts[part + 1] == ' ')) ||
((part + 1 < parts.length && parts[part + 1].substring(0, 1) == ':') &&
(part + 2 >= parts.length || parts[part + 2] == ' ') &&
(part - 1 < 0 || parts[part - 1] == ' ')));
};
DomPredictionHelper.prototype.cleanCss = function(css) {
return css.replace(/\>/, ' > ').replace(/,/, ' , ').replace(/\s+/g, ' ').replace(/^\s+|\s+$/g, '').replace(/,$/, '');
};
DomPredictionHelper.prototype.getPathsFor = function(arr) {
var self = this;
var out = [];
jQuery.each(arr, function() {
if (this && this.nodeName) {
out.push(self.pathOf(this));
}
})
return out;
};
DomPredictionHelper.prototype.predictCss = function(s, r) {
var self = this;
if (s.length == 0) return '';
var selected_paths = self.getPathsFor(s);
var rejected_paths = self.getPathsFor(r);
var css = self.commonCss(selected_paths);
var simplest = self.simplifyCss(css, selected_paths, rejected_paths);
// Do we get off easy?
if (simplest.length > 0) return simplest;
// Okay, then make a union and possibly try to reduce subsets.
var union = '';
jQuery.each(s, function() {
union = self.pathOf(this) + ", " + union;
});
union = self.cleanCss(union);
return self.simplifyCss(union, selected_paths, rejected_paths);
};
DomPredictionHelper.prototype.fragmentSelector = function(selector) {
var self = this;
var out = [];
jQuery.each(selector.split(/\,/), function() {
var out2 = [];
jQuery.each(self.cleanCss(this).split(/\s+/), function() {
out2.push(self.tokenizeCss(this));
});
out.push(out2);
});
return out;
};
// Everything in the first selector must be present in the second.
DomPredictionHelper.prototype.selectorBlockMatchesSelectorBlock = function(selector_block1, selector_block2) {
for (var j = 0; j < selector_block1.length; j++) {
if (jQuery.inArray(selector_block1[j], selector_block2) == -1) {
return false;
}
}
return true;
};
// Assumes list is an array of complete CSS selectors represented as strings.
DomPredictionHelper.prototype.selectorGets = function(type, list, the_selector) {
var self = this;
var result = true;
if (list.length == 0 && type == 'all') return false;
if (list.length == 0 && type == 'none') return true;
var selectors = self.fragmentSelector(the_selector);
var cleaned_list = [];
jQuery.each(list, function() {
cleaned_list.push(self.fragmentSelector(this)[0]);
});
jQuery.each(selectors, function() {
if (!result) return;
var selector = this;
jQuery.each(cleaned_list, function(pos) {
if (!result || this == '') return;
if (self._selectorGets(this, selector)) {
if (type == 'none') result = false;
cleaned_list[pos] = '';
}
});
});
if (type == 'all' && cleaned_list.join('').length > 0) { // Some candidates didn't get matched.
result = false;
}
return result;
};
DomPredictionHelper.prototype._selectorGets = function(candidate_as_blocks, selector_as_blocks) {
var cannot_match = false;
var position = candidate_as_blocks.length - 1;
for (var i = selector_as_blocks.length - 1; i > -1; i--) {
if (cannot_match) break;
if (i == selector_as_blocks.length - 1) { // First element on right.
// If we don't match the first element, we cannot match.
if (!this.selectorBlockMatchesSelectorBlock(selector_as_blocks[i], candidate_as_blocks[position])) cannot_match = true;
position--;
} else {
var found = false;
while (position > -1 && !found) {
found = this.selectorBlockMatchesSelectorBlock(selector_as_blocks[i], candidate_as_blocks[position]);
position--;
}
if (!found) cannot_match = true;
}
}
return !cannot_match;
};
DomPredictionHelper.prototype.invertObject = function(object) {
var new_object = {};
jQuery.each(object, function(key, value) {
new_object[value] = key;
});
return new_object;
};
DomPredictionHelper.prototype.cssToXPath = function(css_string) {
var tokens = this.tokenizeCss(css_string);
if (tokens[0] && tokens[0] == ' ') tokens.splice(0, 1);
if (tokens[tokens.length - 1] && tokens[tokens.length - 1] == ' ') tokens.splice(tokens.length - 1, 1);
var css_block = [];
var out = "";
for(var i = 0; i < tokens.length; i++) {
if (tokens[i] == ' ') {
out += this.cssToXPathBlockHelper(css_block);
css_block = [];
} else {
css_block.push(tokens[i]);
}
}
return out + this.cssToXPathBlockHelper(css_block);
};
// Process a block (html entity, class(es), id, :nth-child()) of css
DomPredictionHelper.prototype.cssToXPathBlockHelper = function(css_block) {
if (css_block.length == 0) return '//';
var out = '//';
var first = css_block[0].substring(0,1);
if (first == ',') return " | ";
if (jQuery.inArray(first, [':', '#', '.']) != -1) {
out += '*';
}
var expressions = [];
var re = null;
for(var i = 0; i < css_block.length; i++) {
var current = css_block[i];
first = current.substring(0,1);
var rest = current.substring(1);
if (first == ':') {
// We only support :nth-child(n) at the moment.
if (re = rest.match(/^nth-child\((\d+)\)$/))
expressions.push('(((count(preceding-sibling::*) + 1) = ' + re[1] + ') and parent::*)');
} else if (first == '.') {
expressions.push('contains(concat( " ", #class, " " ), concat( " ", "' + rest + '", " " ))');
} else if (first == '#') {
expressions.push('(#id = "' + rest + '")');
} else if (first == ',') {
} else {
out += current;
}
}
if (expressions.length > 0) out += '[';
for (var i = 0; i < expressions.length; i++) {
out += expressions[i];
if (i < expressions.length - 1) out += ' and ';
}
if (expressions.length > 0) out += ']';
return out;
};

Refresh Code when Infinite Scroll Is Called

How to I call a JavaScript function when Tumblr's infinite scroll loads more posts?
I figure it would have to be some sort of listener function for when tumblrAutoPager.init us called. I found the infinite scroll code online and don't really understand it.
var tumblrAutoPager = {
url: "http://proto.jp/",
ver: "0.1.7",
rF: true,
gP: {},
pp: null,
ppId: "",
LN: location.hostname,
init: function () {
if ($("autopagerize_icon") || navigator.userAgent.indexOf('iPhone') != -1) return;
var tAP = tumblrAutoPager;
var p = 1;
var lh = location.href;
var lhp = lh.lastIndexOf("/page/");
var lht = lh.lastIndexOf("/tagged/");
if (lhp != -1) {
p = parseInt(lh.slice(lhp + 6));
tAP.LN = lh.slice(7, lhp);
} else if (lht != -1) {
tAP.LN = lh.slice(7);
if (tAP.LN.slice(tAP.LN.length - 1) == "/") tAP.LN = tAP.LN.slice(0, tAP.LN.length - 1);
} else if ("http://" + tAP.LN + "/" != lh) {
return;
};
var gPFncs = [];
gPFncs[0] = function (aE) {
var r = [];
for (var i = 0, l = aE.length; i < l; i++) {
if (aE[i].className == "autopagerize_page_element") {
r = gCE(aE[i]);
break;
}
}
return r;
};
gPFncs[1] = function (aE) {
var r = [];
for (var i = 0, l = aE.length; i < l; i++) {
var arr = aE[i].className ? aE[i].className.split(" ") : null;
if (arr) {
for (var j = 0; j < arr.length; j++) {
arr[j] == "post" ? r.push(aE[i]) : null;
}
}
}
return r;
};
gPFncs[2] = function (aE) {
var r = [];
var tmpId = tAP.ppId ? [tAP.ppId] : ["posts", "main", "container", "content", "apDiv2", "wrapper", "projects"];
for (var i = 0, l = aE.length; i < l; i++) {
for (var j = 0; j < tmpId.length; j++) {
if (aE[i].id == tmpId[j]) {
r = gCE(aE[i]);
tAP.ppId = aE[i].id;
break;
}
}
}
return r;
};
for (var i = 0; i < gPFncs.length; i++) {
var getElems = gPFncs[i](document.body.getElementsByTagName('*'));
if (getElems.length) {
tAP.gP = gPFncs[i];
tAP.pp = getElems[0].parentNode;
break;
}
}
function gCE(pElem) {
var r = [];
for (var i = 0, l = pElem.childNodes.length; i < l; i++) {
r.push(pElem.childNodes.item(i))
}
return r;
}
if (!tAP.pp) {
return;
}
sendRequest.README = {
license: 'Public Domain',
url: 'http://jsgt.org/lib/ajax/ref.htm',
version: 0.516,
author: 'Toshiro Takahashi'
};
function chkAjaBrowser() {
var A, B = navigator.userAgent;
this.bw = {
safari: ((A = B.split('AppleWebKit/')[1]) ? A.split('(')[0].split('.')[0] : 0) >= 124,
konqueror: ((A = B.split('Konqueror/')[1]) ? A.split(';')[0] : 0) >= 3.3,
mozes: ((A = B.split('Gecko/')[1]) ? A.split(' ')[0] : 0) >= 20011128,
opera: ( !! window.opera) && ((typeof XMLHttpRequest) == 'function'),
msie: ( !! window.ActiveXObject) ? ( !! createHttpRequest()) : false
};
return (this.bw.safari || this.bw.konqueror || this.bw.mozes || this.bw.opera || this.bw.msie)
}
function createHttpRequest() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest()
} else {
if (window.ActiveXObject) {
try {
return new ActiveXObject('Msxml2.XMLHTTP')
} catch (B) {
try {
return new ActiveXObject('Microsoft.XMLHTTP')
} catch (A) {
return null
}
}
} else {
return null
}
}
};
function sendRequest(E, R, C, D, F, G, S, A) {
var Q = C.toUpperCase() == 'GET',
H = createHttpRequest();
if (H == null) {
return null
}
if ((G) ? G : false) {
D += ((D.indexOf('?') == -1) ? '?' : '&') + 't=' + (new Date()).getTime()
}
var P = new chkAjaBrowser(),
L = P.bw.opera,
I = P.bw.safari,
N = P.bw.konqueror,
M = P.bw.mozes;
if (typeof E == 'object') {
var J = E.onload;
var O = E.onbeforsetheader
} else {
var J = E;
var O = null
}
if (L || I || M) {
H.onload = function () {
J(H);
H.abort()
}
} else {
H.onreadystatechange = function () {
if (H.readyState == 4) {
J(H);
H.abort()
}
}
}
R = K(R, D);
if (Q) {
D += ((D.indexOf('?') == -1) ? '?' : (R == '') ? '' : '&') + R
}
H.open(C, D, F, S, A);
if ( !! O) {
O(H)
}
B(H);
H.send(R);
function B(T) {
if (!L || typeof T.setRequestHeader == 'function') {
T.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
}
return T
}
function K(X, V) {
var Z = [];
if (typeof X == 'object') {
for (var W in X) {
Y(W, X[W])
}
} else {
if (typeof X == 'string') {
if (X == '') {
return ''
}
if (X.charAt(0) == '&') {
X = X.substring(1, X.length)
}
var T = X.split('&');
for (var W = 0; W < T.length; W++) {
var U = T[W].split('=');
Y(U[0], U[1])
}
}
}
function Y(b, a) {
Z.push(encodeURIComponent(b) + '=' + encodeURIComponent(a))
}
return Z.join('&')
}
return H
}
function addNextPage(oj) {
if (oj.status == 404) {
tAP.remainFlg = false;
return;
}
var d = document.createElement("div");
d.innerHTML = oj.responseText;
var posts = tAP.gP(d.getElementsByTagName("*"));
if (posts.length < 2) {
tAP.rF = false;
return;
}
d = document.createElement("div");
d.className = "tumblrAutoPager_page_info";
tAP.pp.appendChild(d);
for (var i = 0; i < posts.length; i++) {
tAP.pp.appendChild(posts[i]);
}
var footer = $("footer");
footer ? footer.parentNode.appendChild(footer) : null;
tAP.rF = true;
}
watch_scroll();
function watch_scroll() {
var d = document.compatMode == "BackCompat" ? document.body : document.documentElement;
var r = d.scrollHeight - d.clientHeight - (d.scrollTop || document.body.scrollTop);
if (r < d.clientHeight * 2 && tAP.rF) {
tAP.rF = false;
p++;
sendRequest(addNextPage, "", "GET", "http://" + tAP.LN + "/page/" + p, true);
}
setTimeout(arguments.callee, 200);
};
function $(id) {
return document.getElementById(id)
};
},
switchAutoPage: function () {
this.rF = !this.rF;
var aE = document.getElementsByTagName('*');
for (var i = 0, l = aE.length; i < l; i++) {
if (aE[i].className == "tAP_switch") {
aE[i].firstChild.nodeValue = this.rF ? "AutoPage[OFF]" : "AutoPage[ON]";
}
}
}
};
window.addEventListener ? window.addEventListener('load', tumblrAutoPager.init, false) : window.attachEvent ? window.attachEvent("onload", tumblrAutoPager.init) : window.onload = tumblrAutoPager.init;

How can i set customize Form in add event of wdCalender?

i want to set my own customize form in wdCalendar add event like first name last name instead of "what". where in jquery.calendar.js i find quickadd function which one is used when user click on calendar to add event then form appear help of quickadd function but i dont know how to set custom field in this function so please help me
below one is quickadd function of jquery.calender.js
function quickadd(start, end, isallday, pos) {
if ((!option.quickAddHandler && option.quickAddUrl == "") || option.readonly) {
return;
}
var buddle = $("#bbit-cal-buddle");
if (buddle.length == 0) {
var temparr = [];
temparr.push('<div id="bbit-cal-buddle" style="z-index: 180; width: 400px;visibility:hidden;" class="bubble">');
temparr.push('<table class="bubble-table" cellSpacing="0" cellPadding="0"><tbody><tr><td class="bubble-cell-side"><div id="tl1" class="bubble-corner"><div class="bubble-sprite bubble-tl"></div></div>');
temparr.push('<td class="bubble-cell-main"><div class="bubble-top"></div><td class="bubble-cell-side"><div id="tr1" class="bubble-corner"><div class="bubble-sprite bubble-tr"></div></div> <tr><td class="bubble-mid" colSpan="3"><div style="overflow: hidden" id="bubbleContent1"><div><div></div><div class="cb-root">');
temparr.push('<table class="cb-table" cellSpacing="0" cellPadding="0"><tbody><tr><th class="cb-key">');
temparr.push(i18n.xgcalendar.time, ':</th><td class=cb-value><div id="bbit-cal-buddle-timeshow"></div></td></tr><tr><th class="cb-key">');
temparr.push(i18n.xgcalendar.content, ':</th><td class="cb-value"><div class="textbox-fill-wrapper"><div class="textbox-fill-mid"><input id="bbit-cal-what" class="textbox-fill-input"/></div></div><div class="cb-example">');
temparr.push(i18n.xgcalendar.example, '</div></td></tr></tbody></table><input id="bbit-cal-start" type="hidden"/><input id="bbit-cal-end" type="hidden"/><input id="bbit-cal-allday" type="hidden"/><input id="bbit-cal-quickAddBTN" value="');
temparr.push(i18n.xgcalendar.create_event, '" type="button"/> <SPAN id="bbit-cal-editLink" class="lk">');
temparr.push(i18n.xgcalendar.update_detail, ' <StrONG>>></StrONG></SPAN></div></div></div><tr><td><div id="bl1" class="bubble-corner"><div class="bubble-sprite bubble-bl"></div></div><td><div class="bubble-bottom"></div><td><div id="br1" class="bubble-corner"><div class="bubble-sprite bubble-br"></div></div></tr></tbody></table><div id="bubbleClose1" class="bubble-closebutton"></div><div id="prong2" class="prong"><div class=bubble-sprite></div></div></div>');
var tempquickAddHanler = temparr.join("");
temparr = null;
$(document.body).append(tempquickAddHanler);
buddle = $("#bbit-cal-buddle");
var calbutton = $("#bbit-cal-quickAddBTN");
var lbtn = $("#bbit-cal-editLink");
var closebtn = $("#bubbleClose1").click(function() {
$("#bbit-cal-buddle").css("visibility", "hidden");
realsedragevent();
});
calbutton.click(function(e) {
if (option.isloading) {
return false;
}
option.isloading = true;
var what = $("#bbit-cal-what").val();
var datestart = $("#bbit-cal-start").val();
var dateend = $("#bbit-cal-end").val();
var allday = $("#bbit-cal-allday").val();
var f = /^[^\$\<\>]+$/.test(what);
if (!f) {
alert(i18n.xgcalendar.invalid_title);
$("#bbit-cal-what").focus();
option.isloading = false;
return false;
}
var zone = new Date().getTimezoneOffset() / 60 * -1;
var param = [{ "name": "CalendarTitle", value: what },
{ "name": "CalendarStartTime", value: datestart },
{ "name": "CalendarEndTime", value: dateend },
{ "name": "IsAllDayEvent", value: allday },
{ "name": "timezone", value: zone}];
if (option.extParam) {
for (var pi = 0; pi < option.extParam.length; pi++) {
param[param.length] = option.extParam[pi];
}
}
if (option.quickAddHandler && $.isFunction(option.quickAddHandler)) {
option.quickAddHandler.call(this, param);
$("#bbit-cal-buddle").css("visibility", "hidden");
realsedragevent();
}
else {
$("#bbit-cal-buddle").css("visibility", "hidden");
var newdata = [];
var tId = -1;
option.onBeforeRequestData && option.onBeforeRequestData(2);
$.post(option.quickAddUrl, param, function(data) {
if (data) {
if (data.IsSuccess == true) {
option.isloading = false;
option.eventItems[tId][0] = data.Data;
option.eventItems[tId][8] = 1;
render();
option.onAfterRequestData && option.onAfterRequestData(2);
}
else {
option.onRequestDataError && option.onRequestDataError(2, data);
option.isloading = false;
option.onAfterRequestData && option.onAfterRequestData(2);
}
}
}, "json");
newdata.push(-1, what);
var sd = strtodate(datestart);
var ed = strtodate(dateend);
var diff = DateDiff("d", sd, ed);
newdata.push(sd, ed, allday == "1" ? 1 : 0, diff > 0 ? 1 : 0, 0);
newdata.push(-1, 0, "", "");
tId = Ind(newdata);
realsedragevent();
render();
}
});
lbtn.click(function(e) {
if (!option.EditCmdhandler) {
alert("EditCmdhandler" + i18n.xgcalendar.i_undefined);
}
else {
if (option.EditCmdhandler && $.isFunction(option.EditCmdhandler)) {
option.EditCmdhandler.call(this, ['0', $("#bbit-cal-what").val(), $("#bbit-cal-start").val(), $("#bbit-cal-end").val(), $("#bbit-cal-allday").val()]);
}
$("#bbit-cal-buddle").css("visibility", "hidden");
realsedragevent();
}
return false;
});
buddle.mousedown(function(e) { return false });
}
var dateshow = CalDateShow(start, end, !isallday, true);
var off = getbuddlepos(pos.left, pos.top);
if (off.hide) {
$("#prong2").hide()
}
else {
$("#prong2").show()
}
$("#bbit-cal-buddle-timeshow").html(dateshow);
var calwhat = $("#bbit-cal-what").val("");
$("#bbit-cal-allday").val(isallday ? "1" : "0");
$("#bbit-cal-start").val(dateFormat.call(start, i18n.xgcalendar.dateformat.fulldayvalue + " HH:mm"));
$("#bbit-cal-end").val(dateFormat.call(end, i18n.xgcalendar.dateformat.fulldayvalue + " HH:mm"));
buddle.css({ "visibility": "visible", left: off.left, top: off.top });
calwhat.blur().focus(); //add 2010-01-26 blur() fixed chrome
$(document).one("mousedown", function() {
$("#bbit-cal-buddle").css("visibility", "hidden");
realsedragevent();
});
return false;
}
could i add ajax link on add event and display custom form and add data to database ?
is there any solution of this type to direct open popup as in add event as like open in edit event ?
And Here we go..
just copy paste this code in your jquery.form.js
it will provide you and extra field to input text.
jquery.form.js
<script>
(function($) {
$.fn.ajaxSubmit = function(options) {
if (!this.length) {
log('ajaxSubmit: skipping submit process - no element selected');
return this;
}
if (typeof options == 'function')
options = { success: options };
options = $.extend({
url: this.attr('action') || window.location.toString(),
type: this.attr('method') || 'GET'
}, options || {});
var veto = {};
this.trigger('form-pre-serialize', [this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
return this;
}
if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSerialize callback');
return this;
}
var a = this.formToArray(options.semantic);
if (options.data) {
options.extraData = options.data;
for (var n in options.data) {
if(options.data[n] instanceof Array) {
for (var k in options.data[n])
a.push( { name: n, value: options.data[n][k] } )
}
else
a.push( { name: n, value: options.data[n] } );
}
}
if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSubmit callback');
return this;
}
this.trigger('form-submit-validate', [a, this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
return this;
}
var q = $.param(a);
if (options.type.toUpperCase() == 'GET') {
options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
options.data = null;
}
else
options.data = q;
var $form = this, callbacks = [];
if (options.resetForm) callbacks.push(function() { $form.resetForm(); });
if (options.clearForm) callbacks.push(function() { $form.clearForm(); });
if (!options.dataType && options.target) {
var oldSuccess = options.success || function(){};
callbacks.push(function(data) {
$(options.target).html(data).each(oldSuccess, arguments);
});
}
else if (options.success)
callbacks.push(options.success);
options.success = function(data, status) {
for (var i=0, max=callbacks.length; i < max; i++)
callbacks[i].apply(options, [data, status, $form]);
};
var files = $('input:file', this).fieldValue();
var found = false;
for (var j=0; j < files.length; j++)
if (files[j])
found = true;
if (options.iframe || found) {
if ($.browser.safari && options.closeKeepAlive)
$.get(options.closeKeepAlive, fileUpload);
else
fileUpload();
}
else
$.ajax(options);
this.trigger('form-submit-notify', [this, options]);
return this;
function fileUpload() {
var form = $form[0];
if ($(':input[#name=submit]', form).length) {
alert('Error: Form elements must not be named "submit".');
return;
}
var opts = $.extend({}, $.ajaxSettings, options);
var s = jQuery.extend(true, {}, $.extend(true, {}, $.ajaxSettings), opts);
var id = 'jqFormIO' + (new Date().getTime());
var $io = $('<iframe id="' + id + '" name="' + id + '" />');
var io = $io[0];
if ($.browser.msie || $.browser.opera)
io.src = 'javascript:false;document.write("");';
$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
var xhr = {
aborted: 0,
responseText: null,
responseXML: null,
status: 0,
statusText: 'n/a',
getAllResponseHeaders: function() {},
getResponseHeader: function() {},
setRequestHeader: function() {},
abort: function() {
this.aborted = 1;
$io.attr('src','about:blank');
}
};
var g = opts.global;
if (g && ! $.active++) $.event.trigger("ajaxStart");
if (g) $.event.trigger("ajaxSend", [xhr, opts]);
if (s.beforeSend && s.beforeSend(xhr, s) === false) {
s.global && jQuery.active--;
return;
}
if (xhr.aborted)
return;
var cbInvoked = 0;
var timedOut = 0;
var sub = form.clk;
if (sub) {
var n = sub.name;
if (n && !sub.disabled) {
options.extraData = options.extraData || {};
options.extraData[n] = sub.value;
if (sub.type == "image") {
options.extraData[name+'.x'] = form.clk_x;
options.extraData[name+'.y'] = form.clk_y;
}
}
}
setTimeout(function() {
var t = $form.attr('target'), a = $form.attr('action');
$form.attr({
target: id,
method: 'POST',
action: opts.url
});
if (! options.skipEncodingOverride) {
$form.attr({
encoding: 'multipart/form-data',
enctype: 'multipart/form-data'
});
}
if (opts.timeout)
setTimeout(function() { timedOut = true; cb(); }, opts.timeout);
var extraInputs = [];
try {
if (options.extraData)
for (var n in options.extraData)
extraInputs.push(
$('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />')
.appendTo(form)[0]);
$io.appendTo('body');
io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
form.submit();
}
finally {
$form.attr('action', a);
t ? $form.attr('target', t) : $form.removeAttr('target');
$(extraInputs).remove();
}
}, 10);
function cb() {
if (cbInvoked++) return;
io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);
var operaHack = 0;
var ok = true;
try {
if (timedOut) throw 'timeout';
var data, doc;
doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
if (doc.body == null && !operaHack && $.browser.opera) {
operaHack = 1;
cbInvoked--;
setTimeout(cb, 100);
return;
}
xhr.responseText = doc.body ? doc.body.innerHTML : null;
xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
xhr.getResponseHeader = function(header){
var headers = {'content-type': opts.dataType};
return headers[header];
};
if (opts.dataType == 'json' || opts.dataType == 'script') {
var ta = doc.getElementsByTagName('textarea')[0];
xhr.responseText = ta ? ta.value : xhr.responseText;
}
else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
xhr.responseXML = toXml(xhr.responseText);
}
data = $.httpData(xhr, opts.dataType);
}
catch(e){
ok = false;
$.handleError(opts, xhr, 'error', e);
}
if (ok) {
opts.success(data, 'success');
if (g) $.event.trigger("ajaxSuccess", [xhr, opts]);
}
if (g) $.event.trigger("ajaxComplete", [xhr, opts]);
if (g && ! --$.active) $.event.trigger("ajaxStop");
if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');
// clean up
setTimeout(function() {
$io.remove();
xhr.responseXML = null;
}, 100);
};
function toXml(s, doc) {
if (window.ActiveXObject) {
doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = 'false';
doc.loadXML(s);
}
else
doc = (new DOMParser()).parseFromString(s, 'text/xml');
return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
};
};
};
$.fn.ajaxForm = function(options) {
return this.ajaxFormUnbind().bind('submit.form-plugin',function() {
$(this).ajaxSubmit(options);
return false;
}).each(function() {
$(":submit,input:image", this).bind('click.form-plugin',function(e) {
var form = this.form;
form.clk = this;
if (this.type == 'image') {
if (e.offsetX != undefined) {
form.clk_x = e.offsetX;
form.clk_y = e.offsetY;
} else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
var offset = $(this).offset();
form.clk_x = e.pageX - offset.left;
form.clk_y = e.pageY - offset.top;
} else {
form.clk_x = e.pageX - this.offsetLeft;
form.clk_y = e.pageY - this.offsetTop;
}
}
// clear form vars
setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 10);
});
});
};
$.fn.ajaxFormUnbind = function() {
this.unbind('submit.form-plugin');
return this.each(function() {
$(":submit,input:image", this).unbind('click.form-plugin');
});
};
$.fn.formToArray = function(semantic) {
var a = [];
if (this.length == 0) return a;
var form = this[0];
var els = semantic ? form.getElementsByTagName('*') : form.elements;
if (!els) return a;
for(var i=0, max=els.length; i < max; i++) {
var el = els[i];
var n = el.name;
if (!n) continue;
if (semantic && form.clk && el.type == "image") {
// handle image inputs on the fly when semantic == true
if(!el.disabled && form.clk == el)
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
continue;
}
var v = $.fieldValue(el, true);
if (v && v.constructor == Array) {
for(var j=0, jmax=v.length; j < jmax; j++)
a.push({name: n, value: v[j]});
}
else if (v !== null && typeof v != 'undefined')
a.push({name: n, value: v});
}
if (!semantic && form.clk) {
// input type=='image' are not found in elements array! handle them here
var inputs = form.getElementsByTagName("input");
for(var i=0, max=inputs.length; i < max; i++) {
var input = inputs[i];
var n = input.name;
if(n && !input.disabled && input.type == "image" && form.clk == input)
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
}
}
return a;
};
$.fn.formSerialize = function(semantic) {
return $.param(this.formToArray(semantic));
};
$.fn.fieldSerialize = function(successful) {
var a = [];
this.each(function() {
var n = this.name;
if (!n) return;
var v = $.fieldValue(this, successful);
if (v && v.constructor == Array) {
for (var i=0,max=v.length; i < max; i++)
a.push({name: n, value: v[i]});
}
else if (v !== null && typeof v != 'undefined')
a.push({name: this.name, value: v});
});
return $.param(a);
};
$.fn.fieldValue = function(successful) {
for (var val=[], i=0, max=this.length; i < max; i++) {
var el = this[i];
var v = $.fieldValue(el, successful);
if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
continue;
v.constructor == Array ? $.merge(val, v) : val.push(v);
}
return val;
};
$.fieldValue = function(el, successful) {
var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
if (typeof successful == 'undefined') successful = true;
if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
(t == 'checkbox' || t == 'radio') && !el.checked ||
(t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
tag == 'select' && el.selectedIndex == -1))
return null;
if (tag == 'select') {
var index = el.selectedIndex;
if (index < 0) return null;
var a = [], ops = el.options;
var one = (t == 'select-one');
var max = (one ? index+1 : ops.length);
for(var i=(one ? index : 0); i < max; i++) {
var op = ops[i];
if (op.selected) {
var v = $.browser.msie && !(op.attributes['value'].specified) ? op.text : op.value;
if (one) return v;
a.push(v);
}
}
return a;
}
return el.value;
};
$.fn.clearForm = function() {
return this.each(function() {
$('input,select,textarea', this).clearFields();
});
};
$.fn.clearFields = $.fn.clearInputs = function() {
return this.each(function() {
var t = this.type, tag = this.tagName.toLowerCase();
if (t == 'text' || t == 'password' || tag == 'textarea')
this.value = '';
else if (t == 'checkbox' || t == 'radio')
this.checked = false;
else if (tag == 'select')
this.selectedIndex = -1;
});
};
$.fn.resetForm = function() {
return this.each(function() {
if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
this.reset();
});
};
$.fn.enable = function(b) {
if (b == undefined) b = true;
return this.each(function() {
this.disabled = !b
});
};
$.fn.selected = function(select) {
if (select == undefined) select = true;
return this.each(function() {
var t = this.type;
if (t == 'checkbox' || t == 'radio')
this.checked = select;
else if (this.tagName.toLowerCase() == 'option') {
var $sel = $(this).parent('select');
if (select && $sel[0] && $sel[0].type == 'select-one') {
// deselect all other options
$sel.find('option').selected(false);
}
this.selected = select;
}
});
};
function log() {
if ($.fn.ajaxSubmit.debug && window.console && window.console.log)
window.console.log('[jquery.form] ' + Array.prototype.join.call(arguments,''));
};
})(jQuery);
</script>

Using photoswipe run a iframe video in lightbox

i'm using photoswipe to view images in lightbox and also iframe videos too.but is not working in iframe.how can i code to view videos in photoswipe lighbox.
and i try this.
HTML
<html>
<head>
<link rel="stylesheet" href="assets/css/photoswipe.css">
<link rel="stylesheet" href="assets/css/default-skin.css">
</head>
<body>
<div class="video_bg video_gallery" data-pswp-uid="1">
<a class="hide_480" data-med-size="1024x1024" data-med="assets/images/dynamic/video.jpg" data-size="961x577"
href="https://www.youtube.com/embed/i9LZXE--CV0">
<iframe width="961" height="577" frameborder="0" allowfullscreen="1" src="https://www.youtube.com/embed/lEhu2cFvDe8?wmode=opaque?rel=0?autoplay=1&html5=1"></iframe>
</a>
</div>
<script src="assets/js/photoswipe.min.js"></script>
<script src="assets/js/photoswipe-ui-default.min.js"></script>
</body>
</html>
JS
(function() {
var initPhotoSwipeFromDOM = function(gallerySelector) {
var parseThumbnailElements = function(el) {
var thumbElements = el.childNodes,
numNodes = thumbElements.length,
items = [],
el,
childElements,
thumbnailEl,
size,
item;
for(var i = 0; i < numNodes; i++) {
el = thumbElements[i];
// include only element nodes
if(el.nodeType !== 1) {
continue;
}
childElements = el.children;
size = el.getAttribute('data-size').split('x');
// create slide object
item = {
src: el.getAttribute('href'),
w: parseInt(size[0], 10),
h: parseInt(size[1], 10),
author: el.getAttribute('data-author')
};
item.el = el; // save link to element for getThumbBoundsFn
if(childElements.length > 0) {
item.msrc = childElements[0].getAttribute('src'); // thumbnail url
if(childElements.length > 1) {
item.title = childElements[1].innerHTML; // caption (contents of figure)
}
}
var mediumSrc = el.getAttribute('data-med');
if(mediumSrc) {
size = el.getAttribute('data-med-size').split('x');
// "medium-sized" image
item.m = {
src: mediumSrc,
w: parseInt(size[0], 10),
h: parseInt(size[1], 10)
};
}
// original image
item.o = {
src: item.src,
w: item.w,
h: item.h
};
items.push(item);
}
return items;
};
// find nearest parent element
var closest = function closest(el, fn) {
return el && ( fn(el) ? el : closest(el.parentNode, fn) );
};
var onThumbnailsClick = function(e) {
e = e || window.event;
e.preventDefault ? e.preventDefault() : e.returnValue = false;
var eTarget = e.target || e.srcElement;
var clickedListItem = closest(eTarget, function(el) {
return el.tagName === 'A';
});
if(!clickedListItem) {
return;
}
var clickedGallery = clickedListItem.parentNode;
var childNodes = clickedListItem.parentNode.childNodes,
numChildNodes = childNodes.length,
nodeIndex = 0,
index;
for (var i = 0; i < numChildNodes; i++) {
if(childNodes[i].nodeType !== 1) {
continue;
}
if(childNodes[i] === clickedListItem) {
index = nodeIndex;
break;
}
nodeIndex++;
}
if(index >= 0) {
openPhotoSwipe( index, clickedGallery );
}
return false;
};
var photoswipeParseHash = function() {
var hash = window.location.hash.substring(1),
params = {};
if(hash.length < 5) { // pid=1
return params;
}
var vars = hash.split('&');
for (var i = 0; i < vars.length; i++) {
if(!vars[i]) {
continue;
}
var pair = vars[i].split('=');
if(pair.length < 2) {
continue;
}
params[pair[0]] = pair[1];
}
if(params.gid) {
params.gid = parseInt(params.gid, 10);
}
return params;
};
var openPhotoSwipe = function(index, galleryElement, disableAnimation, fromURL) {
var pswpElement = document.querySelectorAll('.pswp')[0],
gallery,
options,
items;
items = parseThumbnailElements(galleryElement);
// define options (if needed)
options = {
galleryUID: galleryElement.getAttribute('data-pswp-uid'),
getThumbBoundsFn: function(index) {
// See Options->getThumbBoundsFn section of docs for more info
var thumbnail = items[index].el.children[0],
pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
rect = thumbnail.getBoundingClientRect();
return {x:rect.left, y:rect.top + pageYScroll, w:rect.width};
},
addCaptionHTMLFn: function(item, captionEl, isFake) {
if(!item.title) {
captionEl.children[0].innerText = '';
return false;
}
captionEl.children[0].innerHTML = item.title + '<br/><small>Photo: ' + item.author + '</small>';
return true;
}
};
if(fromURL) {
if(options.galleryPIDs) {
// parse real index when custom PIDs are used
// http://photoswipe.com/documentation/faq.html#custom-pid-in-url
for(var j = 0; j < items.length; j++) {
if(items[j].pid == index) {
options.index = j;
break;
}
}
} else {
options.index = parseInt(index, 10) - 1;
}
} else {
options.index = parseInt(index, 10);
}
// exit if index not found
if( isNaN(options.index) ) {
return;
}
var radios = document.getElementsByName('gallery-style');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
if(radios[i].id == 'radio-all-controls') {
} else if(radios[i].id == 'radio-minimal-black') {
options.mainClass = 'pswp--minimal--dark';
options.barsSize = {top:0,bottom:0};
options.captionEl = false;
options.fullscreenEl = false;
options.shareEl = false;
options.bgOpacity = 0.85;
options.tapToClose = true;
options.tapToToggleControls = false;
}
break;
}
}
if(disableAnimation) {
options.showAnimationDuration = 0;
}
// Pass data to PhotoSwipe and initialize it
gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
// see: http://photoswipe.com/documentation/responsive-images.html
var realViewportWidth,
useLargeImages = false,
firstResize = true,
imageSrcWillChange;
gallery.listen('beforeResize', function() {
var dpiRatio = window.devicePixelRatio ? window.devicePixelRatio : 1;
dpiRatio = Math.min(dpiRatio, 2.5);
realViewportWidth = gallery.viewportSize.x * dpiRatio;
if(realViewportWidth >= 1200 || (!gallery.likelyTouchDevice && realViewportWidth > 800) || screen.width > 1200 ) {
if(!useLargeImages) {
useLargeImages = true;
imageSrcWillChange = true;
}
} else {
if(useLargeImages) {
useLargeImages = false;
imageSrcWillChange = true;
}
}
if(imageSrcWillChange && !firstResize) {
gallery.invalidateCurrItems();
}
if(firstResize) {
firstResize = false;
}
imageSrcWillChange = false;
});
gallery.listen('gettingData', function(index, item) {
if( useLargeImages ) {
item.src = item.o.src;
item.w = item.o.w;
item.h = item.o.h;
} else {
item.src = item.m.src;
item.w = item.m.w;
item.h = item.m.h;
}
});
gallery.init();
};
// select all gallery elements
var galleryElements = document.querySelectorAll( gallerySelector );
for(var i = 0, l = galleryElements.length; i < l; i++) {
galleryElements[i].setAttribute('data-pswp-uid', i+1);
galleryElements[i].onclick = onThumbnailsClick;
}
// Parse URL and open gallery if it contains #&pid=3&gid=1
var hashData = photoswipeParseHash();
if(hashData.pid && hashData.gid) {
openPhotoSwipe( hashData.pid, galleryElements[ hashData.gid - 1 ], true, true );
}
};
initPhotoSwipeFromDOM('.video_gallery');
})();
i have no idea what to do.i don't know its possible or not. and thanks in advance.
In my jAlbum PhotoSwipe skin, see http://jalbum.net/nl/skins/skin/PhotoSwipe ,
I use a very simple solution for a video:
// build items array
var items = [
{
html: '<video controls autoplay><source src="slides/IMG_4979.mp4" type="video/mp4"></video>'
},
To see it in action, click the 3th thumbnail of the PhotoSwipe skin sample album: http://andrewolff.jalbum.net/Reestdal_PS/

Categories