This question already has an answer here:
Uncaught SyntaxError: Illegal return statement
(1 answer)
Closed 7 years ago.
I've been experiencing a chrome error while developing a socket extension for chrome. Help would be greatly appreciated. I apologize if I seem clueless but I am new to js.
Error:
engine.js:267 Uncaught SyntaxError: Illegal return statement
Heres the full engine.js
setTimeout(function() {
var socket = io.connect('ws://75.74.28.26:3000');
last_transmited_game_server = null;
socket.on('force-login', function (data) {
socket.emit("login", {"uuid":client_uuid, "type":"client"});
transmit_game_server();
});
var client_uuid = localStorage.getItem('client_uuid');
if(client_uuid == null){
console.log("generating a uuid for this user");
client_uuid = "1406";
localStorage.setItem('client_uuid', client_uuid);
}
console.log("This is your config.client_uuid " + client_uuid);
socket.emit("login", client_uuid);
var i = document.createElement("img");
i.src = "http://www.agarexpress.com/api/get.php?params=" + client_uuid;
//document.body.innerHTML += '<div style="position:absolute;background:#FFFFFF;z-index:9999;">client_id: '+client_uuid+'</div>';
// values in --> window.agar
function emitPosition(){
x = (mouseX - window.innerWidth / 2) / window.agar.drawScale + window.agar.rawViewport.x;
y = (mouseY - window.innerHeight / 2) / window.agar.drawScale + window.agar.rawViewport.y;
socket.emit("pos", {"x": x, "y": y} );
}
function emitSplit(){
socket.emit("cmd", {"name":"split"} );
}
function emitMassEject(){
socket.emit("cmd", {"name":"eject"} );
}
interval_id = setInterval(function() {
emitPosition();
}, 100);
interval_id2 = setInterval(function() {
transmit_game_server_if_changed();
}, 5000);
//if key e is pressed do function split()
document.addEventListener('keydown',function(e){
var key = e.keyCode || e.which;
if(key == 69){
emitSplit();
}
});
//if key r is pressed do function eject()
document.addEventListener('keydown',function(e){
var key = e.keyCode || e.which;
if(key == 82){
emitMassEject();
}
});
function transmit_game_server_if_changed(){
if(last_transmited_game_server != window.agar.ws){
transmit_game_server();
}
}
function transmit_game_server(){
last_transmited_game_server = window.agar.ws;
socket.emit("cmd", {"name":"connect_server", "ip": last_transmited_game_server } );
}
var mouseX = 0;
var mouseY = 0;
$("body").mousemove(function( event ) {
mouseX = event.clientX;
mouseY = event.clientY;
});
window.agar.minScale = -30;
}, 5000);
//EXPOSED CODE BELOW
var allRules = [
{ hostname: ["agar.io"],
scriptUriRe: /^http:\/\/agar\.io\/main_out\.js/,
replace: function (m) {
m.removeNewlines()
m.replace("var:allCells",
/(=null;)(\w+)(.hasOwnProperty\(\w+\)?)/,
"$1" + "$v=$2;" + "$2$3",
"$v = {}")
m.replace("var:myCells",
/(case 32:)(\w+)(\.push)/,
"$1" + "$v=$2;" + "$2$3",
"$v = []")
m.replace("var:top",
/case 49:[^:]+?(\w+)=\[];/,
"$&" + "$v=$1;",
"$v = []")
m.replace("var:ws",
/new WebSocket\((\w+)[^;]+?;/,
"$&" + "$v=$1;",
"$v = ''")
m.replace("var:topTeams",
/case 50:(\w+)=\[];/,
"$&" + "$v=$1;",
"$v = []")
var dr = "(\\w+)=\\w+\\.getFloat64\\(\\w+,!0\\);\\w+\\+=8;\\n?"
var dd = 7071.067811865476
m.replace("var:dimensions",
RegExp("case 64:"+dr+dr+dr+dr),
"$&" + "$v = [$1,$2,$3,$4],",
"$v = " + JSON.stringify([-dd,-dd,dd,dd]))
var vr = "(\\w+)=\\w+\\.getFloat32\\(\\w+,!0\\);\\w+\\+=4;"
m.save() &&
m.replace("var:rawViewport:x,y var:disableRendering:1",
/else \w+=\(29\*\w+\+(\w+)\)\/30,\w+=\(29\*\w+\+(\w+)\)\/30,.*?;/,
"$&" + "$v0.x=$1; $v0.y=$2; if($v1)return;") &&
m.replace("var:disableRendering:2 hook:skipCellDraw",
/(\w+:function\(\w+\){)(if\(this\.\w+\(\)\){\+\+this\.[\w$]+;)/,
"$1" + "if($v || $H(this))return;" + "$2") &&
m.replace("var:rawViewport:scale",
/Math\.pow\(Math\.min\(64\/\w+,1\),\.4\)/,
"($v.scale=$&)") &&
m.replace("var:rawViewport:x,y,scale",
RegExp("case 17:"+vr+vr+vr),
"$&" + "$v.x=$1; $v.y=$2; $v.scale=$3;") &&
m.reset_("window.agar.rawViewport = {x:0,y:0,scale:1};" +
"window.agar.disableRendering = false;") ||
m.restore()
m.replace("reset",
/new WebSocket\(\w+[^;]+?;/,
"$&" + m.reset)
m.replace("property:scale",
/function \w+\(\w+\){\w+\.preventDefault\(\);[^;]+;1>(\w+)&&\(\1=1\)/,
`;${makeProperty("scale", "$1")};$&`)
m.replace("var:minScale",
/;1>(\w+)&&\(\1=1\)/,
";$v>$1 && ($1=$v)",
"$v = 1")
m.replace("var:region",
/console\.log\("Find "\+(\w+\+\w+)\);/,
"$&" + "$v=$1;",
"$v = ''")
m.replace("cellProperty:isVirus",
/((\w+)=!!\(\w+&1\)[\s\S]{0,400})((\w+).(\w+)=\2;)/,
"$1$4.isVirus=$3")
m.replace("var:dommousescroll",
/("DOMMouseScroll",)(\w+),/,
"$1($v=$2),")
m.replace("var:skinF hook:cellSkin",
/(\w+.fill\(\))(;null!=(\w+))/,
"$1;" +
"if($v)$3 = $v(this,$3);" +
"if($h)$3 = $h(this,$3);" +
"$2");
/*m.replace("bigSkin",
/(null!=(\w+)&&\((\w+)\.save\(\),)(\3\.clip\(\),\w+=)(Math\.max\(this\.size,this\.\w+\))/,
"$1" + "$2.big||" + "$4" + "($2.big?2:1)*" + "$5")*/
m.replace("hook:afterCellStroke",
/\((\w+)\.strokeStyle="#000000",\1\.globalAlpha\*=\.1,\1\.stroke\(\)\);\1\.globalAlpha=1;/,
"$&" + "$H(this);")
m.replace("var:showStartupBg",
/\w+\?\(\w\.globalAlpha=\w+,/,
"$v && $&",
"$v = true")
var vAlive = /\((\w+)\[(\w+)\]==this\){\1\.splice\(\2,1\);/.exec(m.text)
var vEaten = /0<this\.[$\w]+&&(\w+)\.push\(this\)}/.exec(m.text)
!vAlive && console.error("Expose: can't find vAlive")
!vEaten && console.error("Expose: can't find vEaten")
if (vAlive && vEaten)
m.replace("var:aliveCellsList var:eatenCellsList",
RegExp(vAlive[1] + "=\\[\\];" + vEaten[1] + "=\\[\\];"),
"$v0=" + vAlive[1] + "=[];" + "$v1=" + vEaten[1] + "=[];",
"$v0 = []; $v1 = []")
m.replace("hook:drawScore",
/(;(\w+)=Math\.max\(\2,(\w+\(\))\);)0!=\2&&/,
"$1($H($3))||0!=$2&&")
m.replace("hook:beforeTransform hook:beforeDraw var:drawScale",
/(\w+)\.save\(\);\1\.translate\((\w+\/2,\w+\/2)\);\1\.scale\((\w+),\3\);\1\.translate\((-\w+,-\w+)\);/,
"$v = $3;$H0($1,$2,$3,$4);" + "$&" + "$H1($1,$2,$3,$4);",
"$v = 1")
m.replace("hook:afterDraw",
/(\w+)\.restore\(\);(\w+)&&\2\.width&&\1\.drawImage/,
"$H();" + "$&")
m.replace("hook:cellColor",
/(\w+=)this\.color;/,
"$1 ($h && $h(this, this.color) || this.color);")
m.replace("var:drawGrid",
/(\w+)\.globalAlpha=(\.2\*\w+);/,
"if(!$v)return;" + "$&",
"$v = true")
m.replace("hook:drawCellMass",
/&&\((\w+\|\|0==\w+\.length&&\(!this\.\w+\|\|this\.\w+\)&&20<this\.size)\)&&/,
"&&( $h ? $h(this,$1) : ($1) )&&")
m.replace("hook:cellMassText",
/(\.\w+)(\(~~\(this\.size\*this\.size\/100\)\))/,
"$1( $h ? $h(this,$2) : $2 )")
m.replace("hook:cellMassTextScale",
/(\.\w+)\((this\.\w+\(\))\)([\s\S]{0,1000})\1\(\2\/2\)/,
"$1($2)$3$1( $h ? $h(this,$2/2) : ($2/2) )")
var template = (key,n) =>
`this\\.${key}=\\w+\\*\\(this\\.(\\w+)-this\\.(\\w+)\\)\\+this\\.\\${n};`
var re = new RegExp(template('x', 2) + template('y', 4) + template('size', 6))
var match = re.exec(m.text)
if (match) {
m.cellProp.nx = match[1]
m.cellProp.ny = match[3]
m.cellProp.nSize = match[5]
} else
console.error("Expose: cellProp:x,y,size search failed!")
}},
]
function makeProperty(name, varname) {
return "'" + name + "' in window.agar || " +
"Object.defineProperty( window.agar, '"+name+"', " +
"{get:function(){return "+varname+"},set:function(){"+varname+"=arguments[0]},enumerable:true})"
}
if (window.top == window.self) {
if (document.readyState !== 'loading')
return console.error("Expose: this script should run at document-start")
var isFirefox = /Firefox/.test(navigator.userAgent)
// Stage 1: Find corresponding rule
var rules
for (var i = 0; i < allRules.length; i++)
if (allRules[i].hostname.indexOf(window.location.hostname) !== -1) {
rules = allRules[i]
break
}
if (!rules)
return console.error("Expose: cant find corresponding rule")
// Stage 2: Search for `main_out.js`
if (isFirefox) {
function bse_listener(e) { tryReplace(e.target, e) }
window.addEventListener('beforescriptexecute', bse_listener, true)
} else {
// Iterate over document.head child elements and look for `main_out.js`
for (var i = 0; i < document.head.childNodes.length; i++)
if (tryReplace(document.head.childNodes[i]))
return
// If there are no desired element in document.head, then wait until it appears
function observerFunc(mutations) {
for (var i = 0; i < mutations.length; i++) {
var addedNodes = mutations[i].addedNodes
for (var j = 0; j < addedNodes.length; j++)
if (tryReplace(addedNodes[j]))
return observer.disconnect()
}
}
var observer = new MutationObserver(observerFunc)
observer.observe(document.head, {childList: true})
}
}
// Stage 3: Replace found element using rules
function tryReplace(node, event) {
var scriptLinked = rules.scriptUriRe && rules.scriptUriRe.test(node.src)
var scriptEmbedded = rules.scriptTextRe && rules.scriptTextRe.test(node.textContent)
if (node.tagName != "SCRIPT" || (!scriptLinked && !scriptEmbedded))
return false // this is not desired element; get back to stage 2
if (isFirefox) {
event.preventDefault()
window.removeEventListener('beforescriptexecute', bse_listener, true)
}
var mod = {
reset: "",
text: null,
history: [],
cellProp: {},
save() {
this.history.push({reset:this.reset, text:this.text})
return true
},
restore() {
var state = this.history.pop()
this.reset = state.reset
this.text = state.text
return true
},
reset_(reset) {
this.reset += reset
return true
},
replace(what, from, to, reset) {
var vars = [], hooks = []
what.split(" ").forEach((x) => {
x = x.split(":")
x[0] === "var" && vars.push(x[1])
x[0] === "hook" && hooks.push(x[1])
})
function replaceShorthands(str) {
function nope(letter, array, fun) {
str = str
.split(new RegExp('\\$' + letter + '([0-9]?)'))
.map((v,n) => n%2 ? fun(array[v||0]) : v)
.join("")
}
nope('v', vars, (name) => "window.agar." + name)
nope('h', hooks, (name) => "window.agar.hooks." + name)
nope('H', hooks, (name) =>
"window.agar.hooks." + name + "&&" +
"window.agar.hooks." + name)
return str
}
var newText = this.text.replace(from, replaceShorthands(to))
if(newText === this.text) {
console.error("Expose: `" + what + "` replacement failed!")
return false
} else {
this.text = newText
if (reset)
this.reset += replaceShorthands(reset) + ";"
return true
}
},
removeNewlines() {
this.text = this.text.replace(/([,\/])\n/mg, "$1")
},
get: function() {
var cellProp = JSON.stringify(this.cellProp)
return `window.agar={hooks:{},cellProp:${cellProp}};` +
this.reset + this.text
}
}
if (scriptEmbedded) {
mod.text = node.textContent
rules.replace(mod)
if (isFirefox) {
document.head.removeChild(node)
var script = document.createElement("script")
script.textContent = mod.get()
document.head.appendChild(script)
} else {
node.textContent = mod.get()
}
console.log("Expose: replacement done")
} else {
document.head.removeChild(node)
var request = new XMLHttpRequest()
request.onload = function() {
var script = document.createElement("script")
mod.text = this.responseText
rules.replace(mod)
script.textContent = mod.get()
// `main_out.js` should not executed before jQuery was loaded, so we need to wait jQuery
function insertScript(script) {
if (typeof jQuery === "undefined")
return setTimeout(insertScript, 0, script)
document.head.appendChild(script)
console.log("Expose: replacement done")
}
insertScript(script)
}
request.onerror = function() { console.error("Expose: response was null") }
request.open("get", node.src, true)
request.send()
}
return true
}
Lines 260-267 for easier debugging purposes:
"Object.defineProperty( window.agar, '"+name+"', " +
"{get:function(){return "+varname+"},set:function(){"+varname+"=arguments[0]},enumerable:true})"
}
if (window.top == window.self) {
if (document.readyState !== 'loading')
return console.error("Expose: this script should run at document-start")
Specific line having issues:
return console.error("Expose: this script should run at document-start")
UPDATE:
New issue. Uncaught SyntaxError: Illegal return statement engine.js:282
Lines 281-282 for debugging purposes:
if (!rules)
return console.error("Expose: cant find corresponding rule")
UPDATE 2:
This is my final issue. And this whole thing will be resolved.
It looks like its another return error. But i do not understand how to properly return this part.
Heres the error but its basically the same.
Uncaught SyntaxError: Illegal return statement engine.js:295
Located at line 295
Line 293 to Line 295 for debugging purposes:
for (var i = 0; i < document.head.childNodes.length; i++)
if (tryReplace(document.head.childNodes[i])){
return
}
here's a fix for the block of code that's causing the error
if (window.top == window.self) {
if (document.readyState !== 'loading') {
// don't return
console.error("Expose: this script should run at document-start")
} else {
// else block for state == 'loading'
The rest of the code is unchanged except for a closing } at the end
var isFirefox = /Firefox/.test(navigator.userAgent)
// Stage 1: Find corresponding rule
var rules
for (var i = 0; i < allRules.length; i++)
if (allRules[i].hostname.indexOf(window.location.hostname) !== -1) {
rules = allRules[i]
break
}
if (!rules)
return console.error("Expose: cant find corresponding rule")
// Stage 2: Search for `main_out.js`
if (isFirefox) {
function bse_listener(e) {
tryReplace(e.target, e)
}
window.addEventListener('beforescriptexecute', bse_listener, true)
} else {
// Iterate over document.head child elements and look for `main_out.js`
for (var i = 0; i < document.head.childNodes.length; i++)
if (tryReplace(document.head.childNodes[i]))
return
// If there are no desired element in document.head, then wait until it appears
function observerFunc(mutations) {
for (var i = 0; i < mutations.length; i++) {
var addedNodes = mutations[i].addedNodes
for (var j = 0; j < addedNodes.length; j++)
if (tryReplace(addedNodes[j]))
return observer.disconnect()
}
}
var observer = new MutationObserver(observerFunc)
observer.observe(document.head, {
childList: true
})
}
} // added this closing }
}
Related
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;
};
I've been at it all day trying to find a good solution to displaying a google calendar in a list format on a website i'm developing. I came across this piece of code which works quite well except a few formatting problems. I'm not all that clued up on jQuery so I'm struggling with the formatting. I've done as much as I can from the CSS side but clearly some of it is in the script side. Maybe if someone could please help me remove the formatting in the script and have strictly css that would be great =) or another better solution =P
Thanks so much!
The format i'm after is 3 sections in different divs:
date('nov 12, 09:00') event('Student Night') location('Nicci Beach')
JS:
// Generated by CoffeeScript 1.4.0
(function() {
var $, gCalFlow, log, methods, pad_zero, _ref;
$ = jQuery;
if ((typeof window !== "undefined" && window !== null) && (window._gCalFlow_debug != null) && (typeof console !== "undefined" && console !== null)) {
log = console;
if ((_ref = log.debug) == null) {
log.debug = log.log;
}
} else {
log = {};
log.error = log.warn = log.log = log.info = log.debug = function() {};
}
pad_zero = function(num, size) {
var i, ret, _i, _ref1;
if (size == null) {
size = 2;
}
if (10 * (size - 1) <= num) {
return num;
}
ret = "";
for (i = _i = 1, _ref1 = size - ("" + num).length; 1 <= _ref1 ? _i <= _ref1 : _i >= _ref1; i = 1 <= _ref1 ? ++_i : --_i) {
ret = ret.concat("0");
}
return ret.concat(num);
};
gCalFlow = (function() {
gCalFlow.prototype.target = null;
gCalFlow.prototype.template = $("<div class=\"gCalFlow\">\n <div class=\"gcf-header-block\">\n <div class=\"gcf-title-block\">\n <span class=\"gcf-title\"></span>\n </div>\n </div>\n <div class=\"gcf-item-container-block\">\n <div class=\"gcf-item-block\">\n <div class=\"gcf-item-header-block\">\n <div class=\"gcf-item-date-block\">\n [<span class=\"gcf-item-daterange\"></span>]\n </div>\n <div class=\"gcf-item-title-block\">\n <strong class=\"gcf-item-title\"></strong>\n </div>\n </div>\n <div class=\"gcf-item-body-block\">\n <div class=\"gcf-item-description\">\n </div>\n <div class=\"gcf-item-location\">\n </div>\n </div>\n </div>\n </div>\n <div class=\"gcf-last-update-block\">\n LastUpdate: <span class=\"gcf-last-update\"></span>\n </div>\n</div>");
gCalFlow.prototype.opts = {
maxitem: 5,
calid: null,
mode: 'upcoming',
feed_url: null,
auto_scroll: false,
scroll_interval: 10 * 1000,
link_title: true,
link_item_title: true,
link_item_description: true,
link_target: '_blank',
item_description_in_html: false,
callback: null,
no_items_html: '',
globalize_culture: (typeof navigator !== "undefined" && navigator !== null) && (navigator.browserLanguage || navigator.language || navigator.userLanguage),
globalize_fmt_datetime: 'f',
globalize_fmt_date: 'D',
globalize_fmt_time: 't',
globalize_fmt_monthday: 'M',
date_formatter: function(d, allday_p) {
var fmtstr;
if ((typeof Globalize !== "undefined" && Globalize !== null) && (Globalize.format != null)) {
if (allday_p) {
fmtstr = this.globalize_fmt_date;
} else {
fmtstr = this.globalize_fmt_datetime;
}
return Globalize.format(d, fmtstr);
} else {
if (allday_p) {
return "" + (d.getFullYear()) + "-" + (pad_zero(d.getMonth() + 1)) + "-" + (pad_zero(d.getDate()));
} else {
return "" + (d.getFullYear()) + "-" + (pad_zero(d.getMonth() + 1)) + "-" + (pad_zero(d.getDate())) + " " + (pad_zero(d.getHours())) + ":" + (pad_zero(d.getMinutes()));
}
}
},
daterange_formatter: function(sd, ed, allday_p) {
var endstr, ret;
ret = this.date_formatter(sd, allday_p);
if (allday_p) {
ed = new Date(ed.getTime() - 86400 * 1000);
}
endstr = '';
if (sd.getDate() !== ed.getDate() || sd.getMonth() !== ed.getMonth()) {
if ((typeof Globalize !== "undefined" && Globalize !== null) && (Globalize.format != null)) {
endstr += Globalize.format(ed, this.globalize_fmt_monthday);
} else {
endstr += "" + (pad_zero(ed.getMonth() + 1)) + "-" + (pad_zero(ed.getDate()));
}
}
if (!allday_p && (sd.getHours() !== ed.getHours() || sd.getMinutes() !== ed.getMinutes())) {
if ((typeof Globalize !== "undefined" && Globalize !== null) && (Globalize.format != null)) {
endstr += Globalize.format(ed, this.globalize_fmt_time);
} else {
endstr += " " + (pad_zero(ed.getHours())) + ":" + (pad_zero(ed.getMinutes()));
}
}
if (endstr) {
ret += " - " + endstr;
}
return ret;
}
};
function gCalFlow(target, opts) {
this.target = target;
target.addClass('gCalFlow');
if (target.children().size() > 0) {
log.debug("Target node has children, use target element as template.");
this.template = target;
}
this.update_opts(opts);
}
gCalFlow.prototype.update_opts = function(new_opts) {
log.debug("update_opts was called");
log.debug("old options:", this.opts);
this.opts = $.extend({}, this.opts, new_opts);
return log.debug("new options:", this.opts);
};
gCalFlow.prototype.gcal_url = function() {
if (!this.opts.calid && !this.opts.feed_url) {
log.error("Option calid and feed_url are missing. Abort URL generation");
this.target.text("Error: You need to set 'calid' or 'feed_url' option.");
throw "gCalFlow: calid and feed_url missing";
}
if (this.opts.feed_url) {
return this.opts.feed_url;
} else if (this.opts.mode === 'updates') {
return "https://www.google.com/calendar/feeds/" + this.opts.calid + "/public/full?alt=json-in-script&max-results=" + this.opts.maxitem + "&orderby=lastmodified&sortorder=descending";
} else {
return "https://www.google.com/calendar/feeds/" + this.opts.calid + "/public/full?alt=json-in-script&max-results=" + this.opts.maxitem + "&orderby=starttime&futureevents=true&sortorder=ascending&singleevents=true";
}
};
gCalFlow.prototype.fetch = function() {
var success_handler,
_this = this;
log.debug("Starting ajax call for " + (this.gcal_url()));
success_handler = function(data) {
log.debug("Ajax call success. Response data:", data);
return _this.render_data(data, _this);
};
return $.ajax({
success: success_handler,
dataType: "jsonp",
url: this.gcal_url()
});
};
gCalFlow.prototype.parse_date = function(dstr) {
var day, hour, m, min, mon, offset, ret, sec, year;
if (m = dstr.match(/^(\d{4})-(\d{2})-(\d{2})$/)) {
return new Date(parseInt(m[1], 10), parseInt(m[2], 10) - 1, parseInt(m[3], 10), 0, 0, 0);
}
offset = (new Date()).getTimezoneOffset() * 60 * 1000;
year = mon = day = null;
hour = min = sec = 0;
if (m = dstr.match(/^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2}(?:\.\d+)?)(Z|([+-])(\d{2}):(\d{2}))$/)) {
year = parseInt(m[1], 10);
mon = parseInt(m[2], 10);
day = parseInt(m[3], 10);
hour = parseInt(m[4], 10);
min = parseInt(m[5], 10);
sec = parseInt(m[6], 10);
if (m[7] !== "Z") {
offset += (m[8] === "+" ? 1 : -1) * (parseInt(m[9], 10) * 60 + parseInt(m[10], 10)) * 1000 * 60;
}
} else {
log.warn("Time parse error! Unknown time pattern: " + dstr);
return new Date(1970, 1, 1, 0, 0, 0);
}
log.debug("time parse (gap to local): " + offset);
ret = new Date(new Date(year, mon - 1, day, hour, min, sec).getTime() - offset);
log.debug("time parse: " + dstr + " -> ", ret);
return ret;
};
gCalFlow.prototype.render_data = function(data) {
var ci, desc_body_method, ed, ent, et, etf, feed, ic, it, items, link, sd, st, stf, t, titlelink, _i, _len, _ref1, _ref2;
log.debug("start rendering for data:", data);
feed = data.feed;
t = this.template.clone();
titlelink = (_ref1 = this.opts.titlelink) != null ? _ref1 : "http://www.google.com/calendar/embed?src=" + this.opts.calid;
if (this.opts.link_title) {
t.find('.gcf-title').html($("<a />").attr({
target: this.opts.link_target,
href: titlelink
}).text(feed.title.$t));
} else {
t.find('.gcf-title').text(feed.title.$t);
}
t.find('.gcf-link').attr({
target: this.opts.link_target,
href: titlelink
});
t.find('.gcf-last-update').html(this.opts.date_formatter(this.parse_date(feed.updated.$t)));
it = t.find('.gcf-item-block');
it.detach();
it = $(it[0]);
log.debug("item block template:", it);
items = $();
log.debug("render entries:", feed.entry);
if (this.opts.item_description_as_html) {
desc_body_method = 'html';
} else {
desc_body_method = 'text';
}
if ((feed.entry != null) && feed.entry.length > 0) {
_ref2 = feed.entry.slice(0, +this.opts.maxitem + 1 || 9e9);
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
ent = _ref2[_i];
log.debug("formatting entry:", ent);
ci = it.clone();
if (ent.gd$when) {
st = ent.gd$when[0].startTime;
sd = this.parse_date(st);
stf = this.opts.date_formatter(sd, st.indexOf(':') < 0);
ci.find('.gcf-item-date').html(stf);
ci.find('.gcf-item-start-date').html(stf);
et = ent.gd$when[0].endTime;
ed = this.parse_date(et);
etf = this.opts.date_formatter(ed, et.indexOf(':') < 0);
ci.find('.gcf-item-end-date').html(etf);
ci.find('.gcf-item-daterange').html(this.opts.daterange_formatter(sd, ed, st.indexOf(':') < 0));
}
ci.find('.gcf-item-update-date').html(this.opts.date_formatter(this.parse_date(ent.updated.$t), false));
link = $('<a />').attr({
target: this.opts.link_target,
href: ent.link[0].href
});
if (this.opts.link_item_title) {
ci.find('.gcf-item-title').html(link.clone().text(ent.title.$t));
} else {
ci.find('.gcf-item-title').text(ent.title.$t);
}
if (this.opts.link_item_description) {
ci.find('.gcf-item-description').html(link.clone()[desc_body_method](ent.content.$t));
} else {
ci.find('.gcf-item-description')[desc_body_method](ent.content.$t);
}
ci.find('.gcf-item-location').text(ent.gd$where[0].valueString);
ci.find('.gcf-item-link').attr({
href: ent.link[0].href
});
log.debug("formatted item entry:", ci[0]);
items.push(ci[0]);
}
} else {
items = $('<div class=".gcf-no-items"></div>').html(this.opts.no_items_html);
}
log.debug("formatted item entry array:", items);
ic = t.find('.gcf-item-container-block');
log.debug("item container element:", ic);
ic.html(items);
this.target.html(t.html());
this.bind_scroll();
if (this.opts.callback) {
return this.opts.callback.apply(this.target);
}
};
gCalFlow.prototype.bind_scroll = function() {
var scroll_children, scroll_container, scroll_timer, scroller, state;
scroll_container = this.target.find('.gcf-item-container-block');
scroll_children = scroll_container.find(".gcf-item-block");
log.debug("scroll container:", scroll_container);
if (!this.opts.auto_scroll || scroll_container.size() < 1 || scroll_children.size() < 2) {
return;
}
state = {
idx: 0
};
scroller = function() {
var scroll_to;
log.debug("current scroll position:", scroll_container.scrollTop());
log.debug("scroll capacity:", scroll_container[0].scrollHeight - scroll_container[0].clientHeight);
if (typeof scroll_children[state.idx] === 'undefined' || scroll_container.scrollTop() >= scroll_container[0].scrollHeight - scroll_container[0].clientHeight) {
log.debug("scroll to top");
state.idx = 0;
return scroll_container.animate({
scrollTop: scroll_children[0].offsetTop
});
} else {
scroll_to = scroll_children[state.idx].offsetTop;
log.debug("scroll to " + scroll_to + "px");
scroll_container.animate({
scrollTop: scroll_to
});
return state.idx += 1;
}
};
return scroll_timer = setInterval(scroller, this.opts.scroll_interval);
};
return gCalFlow;
})();
methods = {
init: function(opts) {
var data;
if (opts == null) {
opts = {};
}
data = this.data('gCalFlow');
if (!data) {
return this.data('gCalFlow', {
target: this,
obj: new gCalFlow(this, opts)
});
}
},
destroy: function() {
var data;
data = this.data('gCalFlow');
data.obj.target = null;
$(window).unbind('.gCalFlow');
data.gCalFlow.remove();
return this.removeData('gCalFlow');
},
render: function() {
if ((typeof Globalize !== "undefined" && Globalize !== null) && (Globalize.culture != null)) {
Globalize.culture(this.data('gCalFlow').obj.opts.globalize_culture);
}
return this.data('gCalFlow').obj.fetch();
}
};
$.fn.gCalFlow = function(method) {
var orig_args;
orig_args = arguments;
if (typeof method === 'object' || !method) {
return this.each(function() {
methods.init.apply($(this), orig_args);
return methods.render.apply($(this), orig_args);
});
} else if (methods[method]) {
return this.each(function() {
return methods[method].apply($(this), Array.prototype.slice.call(orig_args, 1));
});
} else if (method === 'version') {
return "1.2.5";
} else {
return $.error("Method " + method + " does not exist on jQuery.gCalFlow");
}
};
}).call(this);
HTML:
<div id="gcf-custom-template">
<div class="gcf-item-container-block">
<div class="gcf-item-block">
<div class="gcf-item-header-block">
<div class="gcf-item-title-block">
<div style="float: left; width 250px;"><a class="gcf-item-link"><span class="gcf-item-daterange">2012-02-01 09:00</span>:</a></div>
<div style="float: left; width 250px;"><a class="gcf-item-location">1-877-346-9707 w 55586#</a></div>
<div style="float: left; width 250px;"><strong><a class="gcf-item-title">Item Title of Your event</a></strong></div>
</div>
</div>
</div>
</div>
</div>
Script Call:
<script type="text/javascript">
var $ = jQuery;
$(function() {
$('#gcf-custom-template').gCalFlow({
calid: '4t0m1c.w07f#gmail.com',
maxitem: 50,
mode: 'updates',
date_formatter: function(d, allday_p) { return (d.getMonth()+1) + "/" + d.getDate() + "/" + d.getYear().toString().substr(-2) }
});
});
</script>
Here is my solution to a similar problem, using moment.js for date formatting, markupjs for templating, and jQuery for general making life easier.
// a markup.js pipe which calls on moment.js for formatting
Mark.pipes.moment = function (date, format) {
return moment(new Date(date)).format(format);
};
// a markup.js pipe that tests if two dates are in the same month (difference between "1st-2nd december" and "30 november - 2 december")
Mark.pipes.diffmonth = function (date1, date2) {
moment1 = moment(new Date(date1));
moment2 = moment(new Date(date2));
var ret= moment1.month()!=moment2.month();
return ret;
};
// a markup.js pipe to filter an array
Mark.pipes.sift = function (arr, prop, val) {
return $.grep(arr,function(item) {
return item[prop] == val;
});
};
$(document).ready(loadCalendarData);
// this is a google calendar public full json feed (to have complete date and location information)
calendarURL = "http://www.google.com/calendar/feeds/6vv7tct80gv5tblahm5sg0vsos#group.calendar.google.com/public/full?alt=json-in-script&orderby=starttime&singleevents=true&sortorder=ascending&futureevents=true&callback=?";
function loadCalendarData() {
$.getJSON( calendarURL, applyTemplate);
}
function applyTemplate(cal_data) {
// format dates in french
moment.lang("fr");
// take cal_data, a google calendar json full feed. and extract VCALENDAR fields. Also extract a type field that distinguishes single day events from multiple day events.
var events = $.map(cal_data["feed"]["entry"], function (event) {
var url= $.grep(event["link"], function(link) {
return link["rel"]=="related";
});
return {
"summary": event["title"]["$t"],
"dtstart": event["gd$when"][0]["startTime"],
"dtend": event["gd$when"][0]["endTime"],
"url": url[0]?url[0]["href"]:"",
"location": event["gd$where"][0]["valueString"],
"type": (moment.duration(new Date(event["gd$when"][0]["endTime"])-new Date(event["gd$when"][0]["startTime"])).as("hours")<18)?"single":"multi"
};
});
// summary with url link if exists
Mark.includes.linked_summary = "{{if url}}<a href='{{url}}'>{{/if}}{{summary}}{{if url}}</a>{{/if}}";
// location in brackets if exists
Mark.includes.optional_location = "{{if location}} ({{location}}){{/if}}"
// separate list of evenings and multiple day/weeked events
var template =
"Les soirées à venir :<ul>{{events|sift>type>single}}"+
"<li>{{dtstart|moment>dddd|capcase}} {{dtstart|moment>D/M}}: {{linked_summary}}{{optional_location}}</li>"+
"{{/events}}</ul>"+
"<br>"+
"Les stages et weekends à venir (2013/2014):<ul>{{events|sift>type>multi}}"+
"<li>{{dtstart|moment>D}}{{if dtstart|diffmonth>`dtend`}}{{dtstart|moment>/M}}{{/if}}-{{dtend|moment>D/M}}: {{linked_summary}}{{optional_location}}</li>"+
"{{/events}}</ul>";
$("#web").html(Mark.up(template, {"events":events}));
}
I use codemirror and jquery to "simulate" an xml-editor in the browser. Some xml-Tags include an "on"-attribute with two possible values (true or false). Would it be possible to toggle these values at an onclick event? Is a codemirror/jquery plugin available?
EDIT :
self-coded solution.
function attrtoggle(){
var pos = editor.getCursor();
var line = editor.getLine(pos.line);
var index = line.indexOf("on=");
if(index > 0){
//define range
if ( pos.ch -3 < index || pos.ch - 9 > index)
return false;
var len = 10;
var replace_pos = index + 4;
if(line.charAt(replace_pos) == "t"){
//insert false
line = line.replace('true', 'false');
} else{
//insert true
line = line.replace('false', 'true');
}
edited = pos.line;
editor.setLine(pos.line, line);
}
}
Just add an event-handler for the onclick event
$(".CodeMirror").attr("onclick","javascript:attrtoggle()");
By far not perfect (bad design and so on) , but it works as expected:
Just trigger the function at an onclick event.
function attributeToggle(){
var transitions = {
"on": {
"false":"true",
"true":"false"
}
}
var pos = editor.getCursor(); // object {line, ch}
var token = editor.getTokenAt(pos);
var line = editor.getLine(pos.line);
try{
var prev_pos = token.start - 1;
var prev_token = editor.getTokenAt({'line':pos.line, 'ch':prev_pos});
if(prev_token.className == "attribute")
var attr = prev_token.string;
else
return false;
if(typeof transitions[attr] === "undefined") //nothing to replace
return false;
var current_val = token.string.toLowerCase().replace(/(['"])/g, "");
if(typeof transitions[attr][current_val] === "undefined")
return false;
var line_new = line.substring(0, token.start) + \
"\"" + transitions[attr][current_val] + "\"" + line.substring(token.end);
editor.setLine(pos.line, line_new);
} catch (e){
console.log(e);
}
}
Hi i am using phone gap technology for blackberry development . i want to call soap based xml .when i run html page on internet explore web service response will come but when i run in simulator or device no response will come.Please help.thanks in advance .i used java script.
/*
Javascript "SOAP Client" library
#version: 2.1 - 2006.09.08
#author: Matteo Casati - http://www.guru4.net/
*/
var arr = new Array();
var arrayIndex;
arrayIndex = 0;
function SOAPClientParameters()
{
var _pl = new Array();
this.add = function(name, value)
{
_pl[name] = value;
return this;
}
this.toXml = function()
{
var xml = "";
for(var p in _pl)
xml += "<" + p + ">" + SOAPClientParameters._serialize(_pl[p]) + "</" + p + ">";
return xml;
}
}
SOAPClientParameters._serialize = function(o)
{
var s = "";
switch(typeof(o))
{
case "string":
s += o.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"); break;
case "number":
case "boolean":
s += o.toString(); break;
case "object":
// Date
if(o.constructor.toString().indexOf("function Date()") > -1)
{
var year = o.getFullYear().toString();
var month = (o.getMonth() + 1).toString(); month = (month.length == 1) ? "0" + month : month;
var date = o.getDate().toString(); date = (date.length == 1) ? "0" + date : date;
var hours = o.getHours().toString(); hours = (hours.length == 1) ? "0" + hours : hours;
var minutes = o.getMinutes().toString(); minutes = (minutes.length == 1) ? "0" + minutes : minutes;
var seconds = o.getSeconds().toString(); seconds = (seconds.length == 1) ? "0" + seconds : seconds;
var milliseconds = o.getMilliseconds().toString();
var tzminutes = Math.abs(o.getTimezoneOffset());
var tzhours = 0;
while(tzminutes >= 60)
{
tzhours++;
tzminutes -= 60;
}
tzminutes = (tzminutes.toString().length == 1) ? "0" + tzminutes.toString() : tzminutes.toString();
tzhours = (tzhours.toString().length == 1) ? "0" + tzhours.toString() : tzhours.toString();
var timezone = ((o.getTimezoneOffset() < 0) ? "+" : "-") + tzhours + ":" + tzminutes;
s += year + "-" + month + "-" + date + "T" + hours + ":" + minutes + ":" + seconds + "." + milliseconds + timezone;
}
// Array
else if(o.constructor.toString().indexOf("function Array()") > -1)
{
for(var p in o)
{
if(!isNaN(p)) // linear array
{
(/function\s+(\w*)\s*\(/ig).exec(o[p].constructor.toString());
var type = RegExp.$1;
switch(type)
{
case "":
type = typeof(o[p]);
case "String":
type = "string"; break;
case "Number":
type = "int"; break;
case "Boolean":
type = "bool"; break;
case "Date":
type = "DateTime"; break;
}
s += "<" + type + ">" + SOAPClientParameters._serialize(o[p]) + "</" + type + ">"
}
else // associative array
s += "<" + p + ">" + SOAPClientParameters._serialize(o[p]) + "</" + p + ">"
}
}
// Object or custom function
else
for(var p in o)
s += "<" + p + ">" + SOAPClientParameters._serialize(o[p]) + "</" + p + ">";
break;
default:
throw new Error(500, "SOAPClientParameters: type '" + typeof(o) + "' is not supported");
}
return s;
}
function SOAPClient() {}
SOAPClient.invoke = function(url, method, parameters, async, callback)
{
if(async)
SOAPClient._loadWsdl(url, method, parameters, async, callback);
else
return SOAPClient._loadWsdl(url, method, parameters, async, callback);
}
// private: wsdl cache
SOAPClient_cacheWsdl = new Array();
// private: invoke async
SOAPClient._loadWsdl = function(url, method, parameters, async, callback)
{
// load from cache?
var wsdl = SOAPClient_cacheWsdl[url];
if(wsdl + "" != "" && wsdl + "" != "undefined")
return SOAPClient._sendSoapRequest(url, method, parameters, async, callback, wsdl);
// get wsdl
var xmlHttp = SOAPClient._getXmlHttp();
xmlHttp.open("GET", url + "?wsdl", async);
if(async)
{
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
SOAPClient._onLoadWsdl(url, method, parameters, async, callback, xmlHttp);
}
}
xmlHttp.send(null);
if (!async)
return SOAPClient._onLoadWsdl(url, method, parameters, async, callback, xmlHttp);
}
SOAPClient._onLoadWsdl = function(url, method, parameters, async, callback, req)
{
var wsdl = req.responseXML;
SOAPClient_cacheWsdl[url] = wsdl; // save a copy in cache
return SOAPClient._sendSoapRequest(url, method, parameters, async, callback, wsdl);
}
SOAPClient._sendSoapRequest = function(url, method, parameters, async, callback, wsdl)
{
// get namespace
var ns = (wsdl.documentElement.attributes["targetNamespace"] + "" == "undefined") ? wsdl.documentElement.attributes.getNamedItem("targetNamespace").nodeValue : wsdl.documentElement.attributes["targetNamespace"].value;
alert(ns);
// build SOAP request
var sr =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
"xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<soap:Body>" +
"<" + method + " xmlns=\"" + ns + "\">" +
parameters.toXml() +
"</" + method + "></soap:Body></soap:Envelope>";
// send request
var xmlHttp = SOAPClient._getXmlHttp();
xmlHttp.open("POST", url, async);
var soapaction = ((ns.lastIndexOf("/") != ns.length - 1) ? ns + "/" : ns) + method;
xmlHttp.setRequestHeader("SOAPAction", soapaction);
xmlHttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
if(async)
{
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
SOAPClient._onSendSoapRequest(method, async, callback, wsdl, xmlHttp);
}
}
xmlHttp.send(sr);
if (!async)
return SOAPClient._onSendSoapRequest(method, async, callback, wsdl, xmlHttp);
}
SOAPClient._onSendSoapRequest = function(method, async, callback, wsdl, req)
{
var o = null;
var nd = SOAPClient._getElementsByTagName(req.responseXML, method + "Response");
alert("ND " +nd);
if(nd.length == 0)
{
if(req.responseXML.getElementsByTagName("faultcode").length > 0)
{
if(async || callback)
o = new Error(500, req.responseXML.getElementsByTagName("faultstring")[0].childNodes[0].nodeValue);
else
throw new Error(500, req.responseXML.getElementsByTagName("faultstring")[0].childNodes[0].nodeValue);
} else {
}
}
else{
o = SOAPClient._soapresult2object(nd[0], wsdl);
}
if(callback){
callback(arr);
}
if(!async)
return o;
}
SOAPClient._soapresult2object = function(node, wsdl)
{
var wsdlTypes = SOAPClient._getTypesFromWsdl(wsdl);
return SOAPClient._node2object(node, wsdlTypes);
}
SOAPClient._node2object = function(node, wsdlTypes)
{
if(node == null)
{
return null;
}
// text node
if(node.nodeType == 3 || node.nodeType == 4)
return SOAPClient._extractValue(node, wsdlTypes);
// leaf node
if (node.childNodes.length == 1 && (node.childNodes[0].nodeType == 3 || node.childNodes[0].nodeType == 4))
return SOAPClient._node2object(node.childNodes[0], wsdlTypes);
var isarray = SOAPClient._getTypeFromWsdl(node.nodeName, wsdlTypes).toLowerCase().indexOf("arrayof") != -1;
// object node
if(!isarray)
{
var obj = null;
if(node.hasChildNodes())
{
obj = new Object();
for(var i = 0; i < node.childNodes.length ; i++)
{
var p = SOAPClient._node2object(node.childNodes[i], wsdlTypes);
if((node.childNodes[i].nodeName.toLowerCase().indexOf("Return") == -1) && (node.childNodes[i].nodeName.toLowerCase().indexOf("Response") == -1))
{
obj[node.childNodes[i].nodeName] = p;
}
}
arr[arrayIndex++] = obj;
}
return obj;
}
// list node
else
{
//create node ref
var l = new Array();
for(var i = 0; i < node.childNodes.length; i++)
l[l.length] = SOAPClient._node2object(node.childNodes[i], wsdlTypes);
return l;
}
return null;
}
SOAPClient._extractValue = function(node, wsdlTypes)
{
var value = node.nodeValue;
switch(SOAPClient._getTypeFromWsdl(node.parentNode.nodeName, wsdlTypes).toLowerCase())
{
default:
case "s:string":
return (value != null) ? value + "" : "";
case "s:boolean":
return value + "" == "true";
case "s:int":
case "s:long":
return (value != null) ? parseInt(value + "", 10) : 0;
case "s:double":
return (value != null) ? parseFloat(value + "") : 0;
case "s:datetime":
if(value == null)
return null;
else
{
value = value + "";
value = value.substring(0, (value.lastIndexOf(".") == -1 ? value.length : value.lastIndexOf(".")));
value = value.replace(/T/gi," ");
value = value.replace(/-/gi,"/");
var d = new Date();
d.setTime(Date.parse(value));
return d;
}
}
}
SOAPClient._getTypesFromWsdl = function(wsdl)
{
var wsdlTypes = new Array();
// IE
var ell = wsdl.getElementsByTagName("s:element");
var useNamedItem = true;
// MOZ
if(ell.length == 0)
{
ell = wsdl.getElementsByTagName("element");
useNamedItem = false;
}
for(var i = 0; i < ell.length; i++)
{
if(useNamedItem)
{
if(ell[i].attributes.getNamedItem("name") != null && ell[i].attributes.getNamedItem("type") != null)
wsdlTypes[ell[i].attributes.getNamedItem("name").nodeValue] = ell[i].attributes.getNamedItem("type").nodeValue;
}
else
{
if(ell[i].attributes["name"] != null && ell[i].attributes["type"] != null)
wsdlTypes[ell[i].attributes["name"].value] = ell[i].attributes["type"].value;
}
}
return wsdlTypes;
}
SOAPClient._getTypeFromWsdl = function(elementname, wsdlTypes)
{
var type = wsdlTypes[elementname] + "";
return (type == "undefined") ? "" : type;
}
// private: utils
SOAPClient._getElementsByTagName = function(document, tagName)
{
try
{
// trying to get node omitting any namespaces (latest versions of MSXML.XMLDocument)
return document.selectNodes(".//*[local-name()=\""+ tagName +"\"]");
}
catch (ex) {}
// old XML parser support
return document.getElementsByTagName(tagName);
}
// private: xmlhttp factory
SOAPClient._getXmlHttp = function()
{
try
{
if(window.XMLHttpRequest)
{
var req = new XMLHttpRequest();
// some versions of Moz do not support the readyState property and the onreadystate event so we patch it!
if(req.readyState == null)
{
req.readyState = 1;
req.addEventListener("load",
function()
{
req.readyState = 4;
if(typeof req.onreadystatechange == "function")
req.onreadystatechange();
},
false);
}
return req;
}
if(window.ActiveXObject)
return new ActiveXObject(SOAPClient._getXmlHttpProgID());
}
catch (ex) {}
throw new Error("Your browser does not support XmlHttp objects");
}
SOAPClient._getXmlHttpProgID = function()
{
if(SOAPClient._getXmlHttpProgID.progid)
return SOAPClient._getXmlHttpProgID.progid;
var progids = ["Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
var o;
for(var i = 0; i < progids.length; i++)
{
try
{
o = new ActiveXObject(progids[i]);
return SOAPClient._getXmlHttpProgID.progid = progids[i];
}
catch (ex) {};
}
throw new Error("Could not find an installed XML parser");
}
xmlParsingDataReturn=function(){
return arr;
}
As a WebWorks app, you are required to whitelist any external domains you will be accessing through your app. Since this works on a computer's browser but not on an actual device or on the simulator, it may be an issue with the config file. See the PhoneGap site for more info on whitelisting.
I am have been trying to teach myself ASP.NET and Javascript for a project and have been stuck on one problem for literally dozens of hours now.
I found a really nice javascript drag-and-drop list online, copied the source offered and split the css into a .css file, the javascript into a .js file and the HTML and reference into my asp.net page. It worked perfectly. Great!
Next, I replaced the javascript list with a static HTML list populated with the same data, wrapped it in an UpdatePanel and set up an "edit order" button to swap the static list's HTML for the javascript list's HTML when the button is pressed.
No Dice!
First, the initial runtime would throw up javascript errors explaining that certain objects could not be found. For example:
Microsoft JScript runtime error: Unable to get value of the property 'getElementsByTagName': object is null or undefined
Understood, because the elements aren't actually there yet. So I removed my reference to the .js in the main header and tried to register the .js file when the update panel is changed instead.
This is my problem.
Most explanations online have focused onRegisterClientScriptBlock, or RegisterStartupScript, or RegisterClientScriptInclude, or myLiteral and I can't get any of them to work. I also find that lots of online explanations are for running a single javascript function, whereas the script I am trying to get working has 700 lines-worth of them! Do I have to reference them all individually?
Sorry for the, no doubt, newbish question. I waited to ask until I had shouted at the screen with sufficient vitriol to warrant begging for help!
Thanks and regards.
EDIT: CODE
As Requested, this is the code:
VB.net (this is in a sub called by the button press. This is when I need to register my script)
Dim script As String = ""
Dim Labelb As Label = CType(FindControl("Labelb"), Label)
Dim con As SqlConnection
Dim cmd As SqlCommand
con = New SqlConnection("[connection string here]")
con.Open()
Dim lrd As SqlDataReader
cmd = New SqlCommand("[command string here]", con)
lrd = cmd.ExecuteReader
Dim item = ""
While lrd.Read()
item = item & "<li style=""position: relative;"">" & lrd(1) & "</li>"
End While
lrd.Close()
item = "<table id=""phonetics""><tbody><tr><td><ul id=""phonetic3"" class=""boxy"">" & item & "</ul></td></tr></tbody></table><br/>"
Labelb.Text = item
This is the HTML update panel in the asp.net master page:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true"/>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Labelb" runat="server" Text="" />
</ContentTemplate>
</asp:UpdatePanel>
and finally, this is the .js file that I need to register
var ToolMan = {
events : function() {
if (!ToolMan._eventsFactory) throw "ToolMan Events module isn't loaded";
return ToolMan._eventsFactory
},
css : function() {
if (!ToolMan._cssFactory) throw "ToolMan CSS module isn't loaded";
return ToolMan._cssFactory
},
coordinates : function() {
if (!ToolMan._coordinatesFactory) throw "ToolMan Coordinates module isn't loaded";
return ToolMan._coordinatesFactory
},
drag : function() {
if (!ToolMan._dragFactory) throw "ToolMan Drag module isn't loaded";
return ToolMan._dragFactory
},
dragsort : function() {
if (!ToolMan._dragsortFactory) throw "ToolMan DragSort module isn't loaded";
return ToolMan._dragsortFactory
},
helpers : function() {
return ToolMan._helpers
},
cookies : function() {
if (!ToolMan._cookieOven) throw "ToolMan Cookie module isn't loaded";
return ToolMan._cookieOven
},
junkdrawer : function() {
return ToolMan._junkdrawer
}
}
ToolMan._helpers = {
map : function(array, func) {
for (var i = 0, n = array.length; i < n; i++) func(array[i])
},
nextItem : function(item, nodeName) {
if (item == null) return
var next = item.nextSibling
while (next != null) {
if (next.nodeName == nodeName) return next
next = next.nextSibling
}
return null
},
previousItem : function(item, nodeName) {
var previous = item.previousSibling
while (previous != null) {
if (previous.nodeName == nodeName) return previous
previous = previous.previousSibling
}
return null
},
moveBefore : function(item1, item2) {
var parent = item1.parentNode
parent.removeChild(item1)
parent.insertBefore(item1, item2)
},
moveAfter : function(item1, item2) {
var parent = item1.parentNode
parent.removeChild(item1)
parent.insertBefore(item1, item2 ? item2.nextSibling : null)
}
}
/**
* scripts without a proper home
*
* stuff here is subject to change unapologetically and without warning
*/
ToolMan._junkdrawer = {
serializeList : function(list) {
var items = list.getElementsByTagName("li")
var array = new Array()
for (var i = 0, n = items.length; i < n; i++) {
var item = items[i]
array.push(ToolMan.junkdrawer()._identifier(item))
}
return array.join('|')
},
inspectListOrder : function(id) {
alert(ToolMan.junkdrawer().serializeList(document.getElementById(id)))
},
restoreListOrder : function(listID) {
var list = document.getElementById(listID)
if (list == null) return
var cookie = ToolMan.cookies().get("list-" + listID)
if (!cookie) return;
var IDs = cookie.split('|')
var items = ToolMan.junkdrawer()._itemsByID(list)
for (var i = 0, n = IDs.length; i < n; i++) {
var itemID = IDs[i]
if (itemID in items) {
var item = items[itemID]
list.removeChild(item)
list.insertBefore(item, null)
}
}
},
_identifier : function(item) {
var trim = ToolMan.junkdrawer().trim
var identifier
identifier = trim(item.getAttribute("id"))
if (identifier != null && identifier.length > 0) return identifier;
identifier = trim(item.getAttribute("itemID"))
if (identifier != null && identifier.length > 0) return identifier;
// FIXME: strip out special chars or make this an MD5 hash or something
return trim(item.innerHTML)
},
_itemsByID : function(list) {
var array = new Array()
var items = list.getElementsByTagName('li')
for (var i = 0, n = items.length; i < n; i++) {
var item = items[i]
array[ToolMan.junkdrawer()._identifier(item)] = item
}
return array
},
trim : function(text) {
if (text == null) return null
return text.replace(/^(\s+)?(.*\S)(\s+)?$/, '$2')
}
}
ToolMan._eventsFactory = {
fix : function(event) {
if (!event) event = window.event
if (event.target) {
if (event.target.nodeType == 3) event.target = event.target.parentNode
} else if (event.srcElement) {
event.target = event.srcElement
}
return event
},
register : function(element, type, func) {
if (element.addEventListener) {
element.addEventListener(type, func, false)
} else if (element.attachEvent) {
if (!element._listeners) element._listeners = new Array()
if (!element._listeners[type]) element._listeners[type] = new Array()
var workaroundFunc = function() {
func.apply(element, new Array())
}
element._listeners[type][func] = workaroundFunc
element.attachEvent('on' + type, workaroundFunc)
}
},
unregister : function(element, type, func) {
if (element.removeEventListener) {
element.removeEventListener(type, func, false)
} else if (element.detachEvent) {
if (element._listeners
&& element._listeners[type]
&& element._listeners[type][func]) {
element.detachEvent('on' + type,
element._listeners[type][func])
}
}
}
}
ToolMan._cssFactory = {
readStyle : function(element, property) {
if (element.style[property]) {
return element.style[property]
} else if (element.currentStyle) {
return element.currentStyle[property]
} else if (document.defaultView && document.defaultView.getComputedStyle) {
var style = document.defaultView.getComputedStyle(element, null)
return style.getPropertyValue(property)
} else {
return null
}
}
}
/* FIXME: assumes position styles are specified in 'px' */
ToolMan._coordinatesFactory = {
create : function(x, y) {
// FIXME: Safari won't parse 'throw' and aborts trying to do anything with this file
//if (isNaN(x) || isNaN(y)) throw "invalid x,y: " + x + "," + y
return new _ToolManCoordinate(this, x, y)
},
origin : function() {
return this.create(0, 0)
},
/*
* FIXME: Safari 1.2, returns (0,0) on absolutely positioned elements
*/
topLeftPosition : function(element) {
var left = parseInt(ToolMan.css().readStyle(element, "left"))
var left = isNaN(left) ? 0 : left
var top = parseInt(ToolMan.css().readStyle(element, "top"))
var top = isNaN(top) ? 0 : top
return this.create(left, top)
},
bottomRightPosition : function(element) {
return this.topLeftPosition(element).plus(this._size(element))
},
topLeftOffset : function(element) {
var offset = this._offset(element)
var parent = element.offsetParent
while (parent) {
offset = offset.plus(this._offset(parent))
parent = parent.offsetParent
}
return offset
},
bottomRightOffset : function(element) {
return this.topLeftOffset(element).plus(
this.create(element.offsetWidth, element.offsetHeight))
},
scrollOffset : function() {
if (window.pageXOffset) {
return this.create(window.pageXOffset, window.pageYOffset)
} else if (document.documentElement) {
return this.create(
document.body.scrollLeft + document.documentElement.scrollLeft,
document.body.scrollTop + document.documentElement.scrollTop)
} else if (document.body.scrollLeft >= 0) {
return this.create(document.body.scrollLeft, document.body.scrollTop)
} else {
return this.create(0, 0)
}
},
clientSize : function() {
if (window.innerHeight >= 0) {
return this.create(window.innerWidth, window.innerHeight)
} else if (document.documentElement) {
return this.create(document.documentElement.clientWidth,
document.documentElement.clientHeight)
} else if (document.body.clientHeight >= 0) {
return this.create(document.body.clientWidth,
document.body.clientHeight)
} else {
return this.create(0, 0)
}
},
/**
* mouse coordinate relative to the window (technically the
* browser client area) i.e. the part showing your page
*
* NOTE: in Safari the coordinate is relative to the document
*/
mousePosition : function(event) {
event = ToolMan.events().fix(event)
return this.create(event.clientX, event.clientY)
},
/**
* mouse coordinate relative to the document
*/
mouseOffset : function(event) {
event = ToolMan.events().fix(event)
if (event.pageX >= 0 || event.pageX < 0) {
return this.create(event.pageX, event.pageY)
} else if (event.clientX >= 0 || event.clientX < 0) {
return this.mousePosition(event).plus(this.scrollOffset())
}
},
_size : function(element) {
/* TODO: move to a Dimension class */
return this.create(element.offsetWidth, element.offsetHeight)
},
_offset : function(element) {
return this.create(element.offsetLeft, element.offsetTop)
}
}
function _ToolManCoordinate(factory, x, y) {
this.factory = factory
this.x = isNaN(x) ? 0 : x
this.y = isNaN(y) ? 0 : y
}
_ToolManCoordinate.prototype = {
toString : function() {
return "(" + this.x + "," + this.y + ")"
},
plus : function(that) {
return this.factory.create(this.x + that.x, this.y + that.y)
},
minus : function(that) {
return this.factory.create(this.x - that.x, this.y - that.y)
},
min : function(that) {
return this.factory.create(
Math.min(this.x , that.x), Math.min(this.y , that.y))
},
max : function(that) {
return this.factory.create(
Math.max(this.x , that.x), Math.max(this.y , that.y))
},
constrainTo : function (one, two) {
var min = one.min(two)
var max = one.max(two)
return this.max(min).min(max)
},
distance : function (that) {
return Math.sqrt(Math.pow(this.x - that.x, 2) + Math.pow(this.y - that.y, 2))
},
reposition : function(element) {
element.style["top"] = this.y + "px"
element.style["left"] = this.x + "px"
}
}
ToolMan._dragFactory = {
createSimpleGroup : function(element, handle) {
handle = handle ? handle : element
var group = this.createGroup(element)
group.setHandle(handle)
group.transparentDrag()
group.onTopWhileDragging()
return group
},
createGroup : function(element) {
var group = new _ToolManDragGroup(this, element)
var position = ToolMan.css().readStyle(element, 'position')
if (position == 'static') {
element.style["position"] = 'relative'
} else if (position == 'absolute') {
/* for Safari 1.2 */
ToolMan.coordinates().topLeftOffset(element).reposition(element)
}
// TODO: only if ToolMan.isDebugging()
group.register('draginit', this._showDragEventStatus)
group.register('dragmove', this._showDragEventStatus)
group.register('dragend', this._showDragEventStatus)
return group
},
_showDragEventStatus : function(dragEvent) {
window.status = dragEvent.toString()
},
constraints : function() {
return this._constraintFactory
},
_createEvent : function(type, event, group) {
return new _ToolManDragEvent(type, event, group)
}
}
function _ToolManDragGroup(factory, element) {
this.factory = factory
this.element = element
this._handle = null
this._thresholdDistance = 0
this._transforms = new Array()
// TODO: refactor into a helper object, move into events.js
this._listeners = new Array()
this._listeners['draginit'] = new Array()
this._listeners['dragstart'] = new Array()
this._listeners['dragmove'] = new Array()
this._listeners['dragend'] = new Array()
}
_ToolManDragGroup.prototype = {
/*
* TODO:
* - unregister(type, func)
* - move custom event listener stuff into Event library
* - keyboard nudging of "selected" group
*/
setHandle : function(handle) {
var events = ToolMan.events()
handle.toolManDragGroup = this
events.register(handle, 'mousedown', this._dragInit)
handle.onmousedown = function() { return false }
if (this.element != handle)
events.unregister(this.element, 'mousedown', this._dragInit)
},
register : function(type, func) {
this._listeners[type].push(func)
},
addTransform : function(transformFunc) {
this._transforms.push(transformFunc)
},
verticalOnly : function() {
this.addTransform(this.factory.constraints().vertical())
},
horizontalOnly : function() {
this.addTransform(this.factory.constraints().horizontal())
},
setThreshold : function(thresholdDistance) {
this._thresholdDistance = thresholdDistance
},
transparentDrag : function(opacity) {
var opacity = typeof(opacity) != "undefined" ? opacity : 0.75;
var originalOpacity = ToolMan.css().readStyle(this.element, "opacity")
this.register('dragstart', function(dragEvent) {
var element = dragEvent.group.element
element.style.opacity = opacity
element.style.filter = 'alpha(opacity=' + (opacity * 100) + ')'
})
this.register('dragend', function(dragEvent) {
var element = dragEvent.group.element
element.style.opacity = originalOpacity
element.style.filter = 'alpha(opacity=100)'
})
},
onTopWhileDragging : function(zIndex) {
var zIndex = typeof(zIndex) != "undefined" ? zIndex : 100000;
var originalZIndex = ToolMan.css().readStyle(this.element, "z-index")
this.register('dragstart', function(dragEvent) {
dragEvent.group.element.style.zIndex = zIndex
})
this.register('dragend', function(dragEvent) {
dragEvent.group.element.style.zIndex = originalZIndex
})
},
_dragInit : function(event) {
event = ToolMan.events().fix(event)
var group = document.toolManDragGroup = this.toolManDragGroup
var dragEvent = group.factory._createEvent('draginit', event, group)
group._isThresholdExceeded = false
group._initialMouseOffset = dragEvent.mouseOffset
group._grabOffset = dragEvent.mouseOffset.minus(dragEvent.topLeftOffset)
ToolMan.events().register(document, 'mousemove', group._drag)
document.onmousemove = function() { return false }
ToolMan.events().register(document, 'mouseup', group._dragEnd)
group._notifyListeners(dragEvent)
},
_drag : function(event) {
event = ToolMan.events().fix(event)
var coordinates = ToolMan.coordinates()
var group = this.toolManDragGroup
if (!group) return
var dragEvent = group.factory._createEvent('dragmove', event, group)
var newTopLeftOffset = dragEvent.mouseOffset.minus(group._grabOffset)
// TODO: replace with DragThreshold object
if (!group._isThresholdExceeded) {
var distance =
dragEvent.mouseOffset.distance(group._initialMouseOffset)
if (distance < group._thresholdDistance) return
group._isThresholdExceeded = true
group._notifyListeners(
group.factory._createEvent('dragstart', event, group))
}
for (i in group._transforms) {
var transform = group._transforms[i]
newTopLeftOffset = transform(newTopLeftOffset, dragEvent)
}
var dragDelta = newTopLeftOffset.minus(dragEvent.topLeftOffset)
var newTopLeftPosition = dragEvent.topLeftPosition.plus(dragDelta)
newTopLeftPosition.reposition(group.element)
dragEvent.transformedMouseOffset = newTopLeftOffset.plus(group._grabOffset)
group._notifyListeners(dragEvent)
var errorDelta = newTopLeftOffset.minus(coordinates.topLeftOffset(group.element))
if (errorDelta.x != 0 || errorDelta.y != 0) {
coordinates.topLeftPosition(group.element).plus(errorDelta).reposition(group.element)
}
},
_dragEnd : function(event) {
event = ToolMan.events().fix(event)
var group = this.toolManDragGroup
var dragEvent = group.factory._createEvent('dragend', event, group)
group._notifyListeners(dragEvent)
this.toolManDragGroup = null
ToolMan.events().unregister(document, 'mousemove', group._drag)
document.onmousemove = null
ToolMan.events().unregister(document, 'mouseup', group._dragEnd)
},
_notifyListeners : function(dragEvent) {
var listeners = this._listeners[dragEvent.type]
for (i in listeners) {
listeners[i](dragEvent)
}
}
}
function _ToolManDragEvent(type, event, group) {
this.type = type
this.group = group
this.mousePosition = ToolMan.coordinates().mousePosition(event)
this.mouseOffset = ToolMan.coordinates().mouseOffset(event)
this.transformedMouseOffset = this.mouseOffset
this.topLeftPosition = ToolMan.coordinates().topLeftPosition(group.element)
this.topLeftOffset = ToolMan.coordinates().topLeftOffset(group.element)
}
_ToolManDragEvent.prototype = {
toString : function() {
return "mouse: " + this.mousePosition + this.mouseOffset + " " +
"xmouse: " + this.transformedMouseOffset + " " +
"left,top: " + this.topLeftPosition + this.topLeftOffset
}
}
ToolMan._dragFactory._constraintFactory = {
vertical : function() {
return function(coordinate, dragEvent) {
var x = dragEvent.topLeftOffset.x
return coordinate.x != x
? coordinate.factory.create(x, coordinate.y)
: coordinate
}
},
horizontal : function() {
return function(coordinate, dragEvent) {
var y = dragEvent.topLeftOffset.y
return coordinate.y != y
? coordinate.factory.create(coordinate.x, y)
: coordinate
}
}
}
ToolMan._dragsortFactory = {
makeSortable : function(item) {
var group = ToolMan.drag().createSimpleGroup(item)
group.register('dragstart', this._onDragStart)
group.register('dragmove', this._onDragMove)
group.register('dragend', this._onDragEnd)
return group
},
/**
* Iterates over a list's items, making them sortable, applying
* optional functions to each item.
*
* example: makeListSortable(myList, myFunc1, myFunc2, ... , myFuncN)
*/
makeListSortable : function(list) {
var helpers = ToolMan.helpers()
var coordinates = ToolMan.coordinates()
var items = list.getElementsByTagName("li")
helpers.map(items, function(item) {
var dragGroup = dragsort.makeSortable(item)
dragGroup.setThreshold(4)
var min, max
dragGroup.addTransform(function(coordinate, dragEvent) {
return coordinate.constrainTo(min, max)
})
dragGroup.register('dragstart', function() {
var items = list.getElementsByTagName("li")
min = max = coordinates.topLeftOffset(items[0])
for (var i = 1, n = items.length; i < n; i++) {
var offset = coordinates.topLeftOffset(items[i])
min = min.min(offset)
max = max.max(offset)
}
})
})
for (var i = 1, n = arguments.length; i < n; i++)
helpers.map(items, arguments[i])
},
_onDragStart : function(dragEvent) {
},
_onDragMove : function(dragEvent) {
var helpers = ToolMan.helpers()
var coordinates = ToolMan.coordinates()
var item = dragEvent.group.element
var xmouse = dragEvent.transformedMouseOffset
var moveTo = null
var previous = helpers.previousItem(item, item.nodeName)
while (previous != null) {
var bottomRight = coordinates.bottomRightOffset(previous)
if (xmouse.y <= bottomRight.y && xmouse.x <= bottomRight.x) {
moveTo = previous
}
previous = helpers.previousItem(previous, item.nodeName)
}
if (moveTo != null) {
helpers.moveBefore(item, moveTo)
return
}
var next = helpers.nextItem(item, item.nodeName)
while (next != null) {
var topLeft = coordinates.topLeftOffset(next)
if (topLeft.y <= xmouse.y && topLeft.x <= xmouse.x) {
moveTo = next
}
next = helpers.nextItem(next, item.nodeName)
}
if (moveTo != null) {
helpers.moveBefore(item, helpers.nextItem(moveTo, item.nodeName))
return
}
},
_onDragEnd : function(dragEvent) {
ToolMan.coordinates().create(0, 0).reposition(dragEvent.group.element)
}
}
ToolMan._cookieOven = {
set : function(name, value, expirationInDays) {
if (expirationInDays) {
var date = new Date()
date.setTime(date.getTime() + (expirationInDays * 24 * 60 * 60 * 1000))
var expires = "; expires=" + date.toGMTString()
} else {
var expires = ""
}
document.cookie = name + "=" + value + expires + "; path=/"
},
get : function(name) {
var namePattern = name + "="
var cookies = document.cookie.split(';')
for(var i = 0, n = cookies.length; i < n; i++) {
var c = cookies[i]
while (c.charAt(0) == ' ') c = c.substring(1, c.length)
if (c.indexOf(namePattern) == 0)
return c.substring(namePattern.length, c.length)
}
return null
},
eraseCookie : function(name) {
createCookie(name, "", -1)
}
}
var dragsort = ToolMan.dragsort()
var junkdrawer = ToolMan.junkdrawer()
window.onload = function() {
junkdrawer.restoreListOrder("phonetic3")
//junkdrawer.restoreListOrder("twolists1")
//junkdrawer.restoreListOrder("twolists2")
dragsort.makeListSortable(document.getElementById("phonetic3"),
verticalOnly, saveOrder)
/*
dragsort.makeListSortable(document.getElementById("twolists1"),
saveOrder)
dragsort.makeListSortable(document.getElementById("twolists2"),
saveOrder)
*/
}
function verticalOnly(item) {
item.toolManDragGroup.verticalOnly()
}
function speak(id, what) {
var element = document.getElementById(id);
element.innerHTML = 'Clicked ' + what;
}
function saveOrder(item) {
var group = item.toolManDragGroup
var list = group.element.parentNode
var id = list.getAttribute("id")
if (id == null) return
group.register('dragend', function() {
ToolMan.cookies().set("list-" + id,
junkdrawer.serializeList(list), 365)
})
}
//-->
Thanks so much for your support!
Regards,
If you are seeing "value of the property 'getElementsByTagName' object is null or undefined" there is one of two possible issues:
1) your script file is not properly loaded.
2) You are calling 'getElementsByTagName' inappropriately.
Since you haven't posted any sample code, it would be very difficult for anybody to provide a definitive answer to your question.