This is confusing me, i am trying to create an identifier like Jquery.
$.ajax
$('object')
the jquery identifier $ can be called without its parenthesis.
Here is some code i got:
function initialized_object(){
this.method = function(){
console.log('this is a string');
}
}
var o = function (args){
if(arguments.length > 0){
//return N$(arguments[0], arguments[1]);
}else{
return new initialized_object();
}
};
o.prototype.constructor.toString = function(){
this.call(this);
}
o().method();
Instead of o().method() i would like to use o.method()
I looked at the jquery source in attempt to find the solution to this with no avail: http://code.jquery.com/jquery-1.11.3.js
This is what i am working with:
( in case you have any ideas )
function N$_no_parameters(){
this.ajax = function(func){
func();
};
};
var N$_np = new N$_no_parameters();
var N$_CURRENT_EVENT_THIS = null;
function N$(selector, within){
this.co = "hi";
if (!Array.prototype.indexOf){
Array.prototype.indexOf = function(elt /*, from*/){
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0) ? Math.ceil(from) : Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++){
if (from in this && this[from] === elt)
return from;
}
return -1;
};
}
var DOM_N$ = function(selector, within, frame){
this.frame = frame || {
win: (within != undefined)? within.contentWindow || this.constructor.caller.arguments[0] : this.constructor.caller.arguments[0],
doc: (within != undefined)? within.contentDocument || this.constructor.caller.arguments[0].document : this.constructor.caller.arguments[0].document,
this: this.constructor.caller.caller.caller.caller.caller
};
if(selector instanceof Object){
if(selector.defaultView == this.frame.win){//selector is document
this.selector = selector;
this.nodes = [this.selector];
}else if(selector.document == document){//selector is window
this.selector = selector;
this.nodes = [this.selector];
}else if(selector instanceof this.frame.this){// selector is this
this.selector = N$_CURRENT_EVENT_THIS.selector;
this.nodes = N$_CURRENT_EVENT_THIS.nodes;//
}else if(selector instanceof Element){//selector is DOM
this.selector = selector;
this.nodes = [this.selector];
}else{
this.selector = selector;
this.nodes = new Array();
for(var key in selector){
var dom_n$_ = N$(selector[key]).nodes;
for(var key_ in dom_n$_){
if(this.nodes.indexOf(dom_n$_[key_]) == -1){
this.nodes.push(dom_n$_[key_]);
}
}
}
}
}else if(typeof selector == "string"){
this.selector = selector;
this.nodes = $prepare(this.selector, this.frame.doc);
}
this.event = function(event_, func){
var that = this;
actionair(function(node){
var events = node.events || {};
if(node.addEventListener){
if((event_) in events){
node.removeEventListener(event_, events[event_], true);
var tmp___ = events[event_];
var tmp__ = function(){
this.bar = "hello";
N$_CURRENT_EVENT_THIS = that;
tmp___(node, event_);
new func(node, event_);
N$_CURRENT_EVENT_THIS = null;
};
node.addEventListener(event_, tmp__, true);
events[event_] = tmp__;
}else{
var tmp__ = function(){
N$_CURRENT_EVENT_THIS = that;
new func(node, event_);
N$_CURRENT_EVENT_THIS = null;
};
node.addEventListener(event_, tmp__, true);
events[event_] = tmp__;
}
}else if(node.attachEvent){
var ie_event = 'on' + event_;
if(event_ in events){
node.attachEvent(ie_event, function(){
N$_CURRENT_EVENT_THIS = that;
new func(node, event_);
events[event_](node, event_);
N$_CURRENT_EVENT_THIS = null;
});
}else{
node.attachEvent(ie_event, function(){
N$_CURRENT_EVENT_THIS = that;
new func(node, event_);
N$_CURRENT_EVENT_THIS = null;
});
}
events[event_] = func;
}
node.events = events;
}, this);
}
this.removeEvent = function(event_){
actionair(function(node, that){
var events = node.events || {};
if(node.removeEventListener){
if((event_) in events){
node.removeEventListener(event_, events[event_], true);
events[event_] = null;
}
}else if(node.detachEvent){
var ie_event = 'on' + event_;
if((event_) in events){
node.detachEvent(ie_event, events[event_]);
delete events[event_];
}
}
}, this);
}
this.eachNode = function(func){
actionair(function(node, that){
N$_CURRENT_EVENT_THIS = N$(node);
new func(node);
}, this);
}
this.css = function(attr, value){
N$_CURRENT_EVENT_THIS = this;
var attribute = "";
if(attr.indexOf('-') !== -1){
var split_attr = attr.split('-');
for (var i = 0; i < split_attr.length; i++) {
if(i != 0)
attribute += split_attr[i].charAt(0).toUpperCase() + split_attr[i].slice(1);
else
attribute += split_attr[i].charAt(0).toLowerCase() + split_attr[i].slice(1);
};
}else{
attribute = attr;
}
var properties = new Array();
actionair(function(node, that){
if(typeof value != 'undefined'){
node.style[attribute] = value;
}
if (!that.frame.win.getComputedStyle) {//IE
that.frame.win.getComputedStyle = function(el, pseudo) {
that.el = el;
that.getPropertyValue = function(prop) {
var re = /(\-([a-z]){1})/g;
if (prop == 'float') prop = 'styleFloat';
if (re.test(prop)) {
prop = prop.replace(re, function () {
return arguments[2].toUpperCase();
});
}
return el.currentStyle[prop] ? el.currentStyle[prop] : null;
}
return that;
}
}
properties.push(that.frame.win.getComputedStyle(node, null).getPropertyValue(attr));
}, this);
return properties;
};
this.text = function(str){
actionair(function(node, that){
node.innerHTML = '';
node.appendChild(that.frame.doc.createTextNode(str));
}, this);
};
this.appendNode = function(tagname, innerHTML){
actionair(function(node, that){
var new_node = that.frame.doc.createElement(tagname);
new_node.innerHTML = innerHTML;
node.appendChild(new_node);
}, this);
};
this.innerHTML = function(innerHTML){
actionair(function(node, that){
node.innerHTML = innerHTML;
}, this);
};
this.removeNode = function(){
actionair(function(node, that){
node.parentNode.removeChild(node);
}, this);
};
this.animate = function(func, from, to, speed){
var that = this;
actionair(function(node, that){
(function animate(func, from, to, speed, node){
if(from >= to){
N$_CURRENT_EVENT_THIS = that;
new func(node, to);
N$_CURRENT_EVENT_THIS = null;
}else{
N$_CURRENT_EVENT_THIS = that;
new func(node, from);
N$_CURRENT_EVENT_THIS = null;
setTimeout(
function(){
animate(func, from+1, to, speed, node);
}, speed
);
}
})(func, from, to, speed, node);
}, this);
}
function actionair(func, that){
for (var i = 0; i < that.nodes.length; i++) {
(function(i_){
N$_CURRENT_EVENT_THIS = that;
new func(that.nodes[i_], that);
N$_CURRENT_EVENT_THIS = null;
})(i);
}
}
function $prepare(str, doc){
str = str.replace(/(\s+>\s+)/g,'>');
str = str.replace(/(\s+)/g,' ');
var str_ = str;
var querys = str.split(/[\s\>]+/);
var querys_des = Array();
var ascender = new Array();
for (var i = 0; i < str_.length; i++) {
if(str_[i] == ">" || str_[i] == " "){
var tmp_ = (str_[i] == ">")? 'next_child' : 'ascended';
ascender.push( tmp_);
}
};
var recognizes = new Array();
for (var i = 0; i < querys.length; i++) {
var asc_child = null;
asc_child = ascender[i-1];
var tmp_ = {
"selector": querys[i],
"i":i
};
recognizes[i] = recognize(querys[i], doc);
if(i != 0){
tmp_["asc_child"] = asc_child;
}else{
tmp_["base_selector"] = true;
}
querys_des.push(tmp_);
};
return $select(querys_des, recognizes, doc);
}
function $select(querys_des, recognizes, parent_, doc){
var parents = parent_ || null;
for (var i = 0; i < querys_des.length; i++) {
if('base_selector' in querys_des[i]){
parents = recognizes[querys_des[i]['i']];
}else if('asc_child' in querys_des[i]){
var cur_children = recognizes[querys_des[i]['i']];
if(querys_des[i]['asc_child'] == 'next_child'){
var compatible = compatible_children(parents, cur_children, querys_des[i]['asc_child'], doc);
parents = compatible;
}else if(querys_des[i]['asc_child'] == 'ascended'){
var compatible = compatible_children(parents, cur_children, querys_des[i]['asc_child'], doc);
parents = compatible;
}
}
};
return parents;
}
function compatible_children(parents, children, type, doc){
var ret = new Array();
for (var a = 0; a < parents.length; a++) {
for (var b = 0; b < children.length; b++) {
if(type == 'next_child'){
if(parents[a] == children[b].parentNode){
if(ret.indexOf(children[b]) == -1)
ret.push(children[b]);
}
}else if(type == 'ascended'){
if(isin(parents[a], children[b], doc)){
if(ret.indexOf(children[b]) == -1)
ret.push(children[b]);
}
}
}
}
return ret;
}
function isin(parent, child, doc){
var child_ = child;
var ret = new Array();
while((child_ = child_.parentNode) && child_ != doc.body){
if(parent == child_){
return true;
}
}
return false;
}
function recognize(str, doc){
var identifier = new Array();
var id_ = false;
var class_ = false;
var dom_ = false;
if(str.indexOf("#") >= 0){
id_ = true;
var tmp = str.split("#")[1];
if(str.indexOf(".") >= 0){
identifier['ID'] = tmp.split(".")[0];
}else{
identifier['ID'] = tmp;
}
}
if(str.indexOf(".") >= 0){
class_ = true;
var tmp = str.split(".")[1];
if(str.indexOf("#") >= 0){
identifier['CLASS'] = tmp.split("#")[0];
}else{
identifier['CLASS'] = tmp;
}
}
if(id_ && class_){
if(str.indexOf("#") < str.indexOf(".")){
var tmp = str.split("#")[0];
if(tmp.length > 0){
dom_ = true;
identifier['DOM'] = tmp;
}
}else{
var tmp = str.split(".")[0];
if(tmp.length > 0){
dom_ = true;
identifier['DOM'] = tmp;
}
}
}else if(id_){
var tmp = str.split("#")[0];
if(tmp.length > 0){
dom_ = true;
identifier['DOM'] = tmp;
}
}else if(class_){
var tmp = str.split(".")[0];
if(tmp.length > 0){
dom_ = true;
identifier['DOM'] = tmp;
}
}else{
if(str.length > 0){
dom_ = true;
identifier['DOM'] = str;
}
}
var x;
if(class_){
if(typeof doc.getElementsByClassName !== 'function') {//Old browsers
x = doc.body.getElementsByTagName("*");
}else{
x = doc.getElementsByClassName(identifier['CLASS']);
}
}else if(dom_){
x = doc.getElementsByTagName(identifier['DOM']);
}else if(id_){
x = doc.body.getElementsByTagName("*");
for (var i = 0; i < x.length; i++) {
if(x[i].getAttribute("id") != identifier['ID']){
delete x[i];
}
};
}
var elements = new Array();
for (var i = 0; i < x.length; i++) {
if(id_ && class_){
if(x[i].getAttribute("id") == identifier["ID"] && x[i].getAttribute("class") == identifier["CLASS"]){
if(dom_){
if(x[i].tagName.toLowerCase() == identifier['DOM'].toLowerCase()){
elements.push(x[i]);
}
}else{
elements.push(x[i]);
}
}
}else if(id_){
if(x[i].getAttribute("id") == identifier["ID"]){
if(dom_){
if(x[i].tagName.toLowerCase() == identifier['DOM'].toLowerCase()){
elements.push(x[i]);
}
}else{
elements.push(x[i]);
}
}
}else if(class_){
if(x[i].getAttribute("class") == identifier["CLASS"]){
if(dom_){
if(x[i].tagName.toLowerCase() == identifier['DOM'].toLowerCase()){
elements.push(x[i]);
}
}else{
elements.push(x[i]);
}
}
}else{
if(dom_){
if(x[i].tagName.toLowerCase() == identifier['DOM'].toLowerCase()){
elements.push(x[i]);
}
}else{
elements.push(x[i]);
}
}
};
return elements;
}
};
var selectors = new Array();
console.log('arguments' + arguments.length);
if(arguments.length > 0){
return new (function(selector, within){
if(typeof within == typeof {}){
if(within.nodes != undefined){
var ret = new Array();
for (var i = within.nodes.length - 1; i >= 0; i--) {
ret.push(do_node_select(selector, within.nodes[i]));
};
return ret;
}else if(
typeof Node === "object" ? within instanceof Node :
within && typeof within === "object" && typeof within.nodeType === "number" && typeof within.nodeName==="string"
){
return do_node_select(selector, within);
}
}
return do_node_select(selector, undefined);
function do_node_select(selector, node){
var N$_new = new ( function(win, doc){
return new DOM_N$(selector, node || undefined);
})(window);
var N$_ = null;
if(selectors.length > 0){
for (var i = selectors.length - 1; i >= 0; i--) {
if(selectors[i].selector == selector){
var not_in = new Array();
for (var b = N$_new.nodes.length - 1; b >= 0; b--) {
if(selectors[i].nodes.indexOf(N$_new.nodes[b]) == -1){
not_in.push(N$_new.nodes[b]);
}
};
for (var a = not_in.length - 1; a >= 0; a--) {
if(selectors[i].nodes.indexOf(not_in[a]) == -1){
selectors[i].nodes.push(not_in[a]);
}
};
N$_ = selectors[i];
break;
}else{
N$_ = N$_new;
}
};
}else{
N$_ = N$_new;
if(N$_.nodes.length > 0){
selectors.push(N$_);
}
}
return N$_;
}
})(selector, within || undefined);
}else{
return N$_np;
}
};
N$(window).event('load', function(){
N$.ajax(function(){ // this will not work but using N$().ajax will
console.log('aaa');
});
});
This is a library i am making similar to Jquery, it selects nodes & handles events and more. the reason i would like to call my ajax function without parenthesis is for clarity.
the jquery identifier $ can be called without its parenthesis.
No. The function isn't being called.
Functions are objects. Objects can have properties. This is simply accessing a property of the function object.
function foo() {
return 1;
}
foo.bar = 2;
alert(foo.bar);
alert(foo());
Instead of o().method() i would like to use o.method()
Those statements mean different things.
The first calls the method method of the value that is returned when you call the o function.
The second calls the method method of the o function itself.
The second doesn't touch the initialised object (or even create one) at all.
$ is a function. But functions in JavaScript are also objects, which in-turn can have functions.
Perhaps this pattern is closer to what you are looking for:
var o = {
method: function() {
}
};
o.method();
Every time you call o() you get a new instance that can behave differently based on how you call it.
If you were to just call o.method, how would it know which reference to use? To be like jQuery, you would do
o = o() // or o('something')
which would create a global singleton o that you could then call o.method.
Quentim's answer is completely correct. You're just acessing a property, no big deal. I just wanted to add that there's a way to "call a function without parenthesis" if you're using getters:
window.__defineGetter__("$", function() {
//This gets executed when you access $
console.log('oh hai');
return { foo: 'bar' }
});
Not that this should be done at all, but this is a way of achieving what's in the question title
Related
I have been searching for quite a while now and I'm not able to find a simple JS library to make a network in which:
The nodes have labels
The edge thickness is proportional to the weight
Able to spread the nodes so that it doesn't get messy.
I found a script on bl.ocks.org which fits my needs, but when I use a lot of nodes it's getting quite messy:
I use this as input:
target,source,weight
woooooow,notgood,70.0
woooooow,gainzz,32.004950495049506
woooooow,test,33.86138613861386
woooooow,peanutss,20.866336633663366
nicecode,woooooow,22.103960396039604
woooooow,oreo,20.742574257425744
bread,woooooow,37.945544554455445
jam,nutella,20.123762376237625
bread,nutsarelol,20.866336633663366
etc
Question
Any ideas which code/library I can use to create a graph like the graph above but with more spreading of the nodes?
JS code
/*
Author: Corneliu S. (github.com/upphiminn)
This is a javascript implementation of the Louvain
community detection algorithm (http://arxiv.org/abs/0803.0476)
Based on https://bitbucket.org/taynaud/python-louvain/overview
*/
(function(){
jLouvain = function(){
//Constants
var __PASS_MAX = -1
var __MIN = 0.0000001
//Local vars
var original_graph_nodes;
var original_graph_edges;
var original_graph = {};
var partition_init;
//Helpers
function make_set(array){
var set = {};
array.forEach(function(d,i){
set[d] = true;
});
return Object.keys(set);
};
function obj_values(obj){
var vals = [];
for( var key in obj ) {
if ( obj.hasOwnProperty(key) ) {
vals.push(obj[key]);
}
}
return vals;
};
function get_degree_for_node(graph, node){
var neighbours = graph._assoc_mat[node] ? Object.keys(graph._assoc_mat[node]) : [];
var weight = 0;
neighbours.forEach(function(neighbour,i){
var value = graph._assoc_mat[node][neighbour] || 1;
if(node == neighbour)
value *= 2;
weight += value;
});
return weight;
};
function get_neighbours_of_node(graph, node){
if(typeof graph._assoc_mat[node] == 'undefined')
return [];
var neighbours = Object.keys(graph._assoc_mat[node]);
return neighbours;
}
function get_edge_weight(graph, node1, node2){
return graph._assoc_mat[node1] ? graph._assoc_mat[node1][node2] : undefined;
}
function get_graph_size(graph){
var size = 0;
graph.edges.forEach(function(edge){
size += edge.weight;
});
return size;
}
function add_edge_to_graph(graph, edge){
update_assoc_mat(graph, edge);
var edge_index = graph.edges.map(function(d){
return d.source+'_'+d.target;
}).indexOf(edge.source+'_'+edge.target);
if(edge_index != -1)
graph.edges[edge_index].weight = edge.weight;
else
graph.edges.push(edge);
}
function make_assoc_mat(edge_list){
var mat = {};
edge_list.forEach(function(edge, i){
mat[edge.source] = mat[edge.source] || {};
mat[edge.source][edge.target] = edge.weight;
mat[edge.target] = mat[edge.target] || {};
mat[edge.target][edge.source] = edge.weight;
});
return mat;
}
function update_assoc_mat(graph, edge){
graph._assoc_mat[edge.source] = graph._assoc_mat[edge.source] || {};
graph._assoc_mat[edge.source][edge.target] = edge.weight;
graph._assoc_mat[edge.target] = graph._assoc_mat[edge.target] || {};
graph._assoc_mat[edge.target][edge.source] = edge.weight;
}
function clone(obj){
if(obj == null || typeof(obj) != 'object')
return obj;
var temp = obj.constructor();
for(var key in obj)
temp[key] = clone(obj[key]);
return temp;
}
//Core-Algorithm Related
function init_status(graph, status, part){
status['nodes_to_com'] = {};
status['total_weight'] = 0;
status['internals'] = {};
status['degrees'] = {};
status['gdegrees'] = {};
status['loops'] = {};
status['total_weight'] = get_graph_size(graph);
if(typeof part == 'undefined'){
graph.nodes.forEach(function(node,i){
status.nodes_to_com[node] = i;
var deg = get_degree_for_node(graph, node);
if (deg < 0)
throw 'Bad graph type, use positive weights!';
status.degrees[i] = deg;
status.gdegrees[node] = deg;
status.loops[node] = get_edge_weight(graph, node, node) || 0;
status.internals[i] = status.loops[node];
});
}else{
graph.nodes.forEach(function(node,i){
var com = part[node];
status.nodes_to_com[node] = com;
var deg = get_degree_for_node(graph, node);
status.degrees[com] = (status.degrees[com] || 0) + deg;
status.gdegrees[node] = deg;
var inc = 0.0;
var neighbours = get_neighbours_of_node(graph, node);
neighbours.forEach(function(neighbour, i){
var weight = graph._assoc_mat[node][neighbour];
if (weight <= 0){
throw "Bad graph type, use positive weights";
}
if(part[neighbour] == com){
if (neighbour == node){
inc += weight;
}else{
inc += weight/2.0;
}
}
});
status.internals[com] = (status.internals[com] || 0) + inc;
});
}
}
function __modularity(status){
var links = status.total_weight;
var result = 0.0;
var communities = make_set(obj_values(status.nodes_to_com));
communities.forEach(function(com,i){
var in_degree = status.internals[com] || 0 ;
var degree = status.degrees[com] || 0 ;
if(links > 0){
result = result + in_degree / links - Math.pow((degree / (2.0*links)), 2);
}
});
return result;
}
function __neighcom(node, graph, status){
// compute the communities in the neighb. of the node, with the graph given by
// node_to_com
var weights = {};
var neighboorhood = get_neighbours_of_node(graph, node);//make iterable;
neighboorhood.forEach(function(neighbour, i){
if(neighbour != node){
var weight = graph._assoc_mat[node][neighbour] || 1;
var neighbourcom = status.nodes_to_com[neighbour];
weights[neighbourcom] = (weights[neighbourcom] || 0) + weight;
}
});
return weights;
}
function __insert(node, com, weight, status){
//insert node into com and modify status
status.nodes_to_com[node] = +com;
status.degrees[com] = (status.degrees[com] || 0) + (status.gdegrees[node]||0);
status.internals[com] = (status.internals[com] || 0) + weight + (status.loops[node]||0);
}
function __remove(node, com, weight, status){
//remove node from com and modify status
status.degrees[com] = ((status.degrees[com] || 0) - (status.gdegrees[node] || 0));
status.internals[com] = ((status.internals[com] || 0) - weight -(status.loops[node] ||0));
status.nodes_to_com[node] = -1;
}
function __renumber(dict){
var count = 0;
var ret = clone(dict); //deep copy :)
var new_values = {};
var dict_keys = Object.keys(dict);
dict_keys.forEach(function(key){
var value = dict[key];
var new_value = typeof new_values[value] =='undefined' ? -1 : new_values[value];
if(new_value == -1){
new_values[value] = count;
new_value = count;
count = count + 1;
}
ret[key] = new_value;
});
return ret;
}
function __one_level(graph, status){
//Compute one level of the Communities Dendogram.
var modif = true,
nb_pass_done = 0,
cur_mod = __modularity(status),
new_mod = cur_mod;
while (modif && nb_pass_done != __PASS_MAX){
cur_mod = new_mod;
modif = false;
nb_pass_done += 1
graph.nodes.forEach(function(node,i){
var com_node = status.nodes_to_com[node];
var degc_totw = (status.gdegrees[node] || 0) / (status.total_weight * 2.0);
var neigh_communities = __neighcom(node, graph, status);
__remove(node, com_node, (neigh_communities[com_node] || 0.0), status);
var best_com = com_node;
var best_increase = 0;
var neigh_communities_entries = Object.keys(neigh_communities);//make iterable;
neigh_communities_entries.forEach(function(com,i){
var incr = neigh_communities[com] - (status.degrees[com] || 0.0) * degc_totw;
if (incr > best_increase){
best_increase = incr;
best_com = com;
}
});
__insert(node, best_com, neigh_communities[best_com] || 0, status);
if(best_com != com_node)
modif = true;
});
new_mod = __modularity(status);
if(new_mod - cur_mod < __MIN)
break;
}
}
function induced_graph(partition, graph){
var ret = {nodes:[], edges:[], _assoc_mat: {}};
var w_prec, weight;
//add nodes from partition values
var partition_values = obj_values(partition);
ret.nodes = ret.nodes.concat(make_set(partition_values)); //make set
graph.edges.forEach(function(edge,i){
weight = edge.weight || 1;
var com1 = partition[edge.source];
var com2 = partition[edge.target];
w_prec = (get_edge_weight(ret, com1, com2) || 0);
var new_weight = (w_prec + weight);
add_edge_to_graph(ret, {'source': com1, 'target': com2, 'weight': new_weight});
});
return ret;
}
function partition_at_level(dendogram, level){
var partition = clone(dendogram[0]);
for(var i = 1; i < level + 1; i++ )
Object.keys(partition).forEach(function(key,j){
var node = key;
var com = partition[key];
partition[node] = dendogram[i][com];
});
return partition;
}
function generate_dendogram(graph, part_init){
if(graph.edges.length == 0){
var part = {};
graph.nodes.forEach(function(node,i){
part[node] = node;
});
return part;
}
var status = {};
init_status(original_graph, status, part_init);
var mod = __modularity(status);
var status_list = [];
__one_level(original_graph, status);
var new_mod = __modularity(status);
var partition = __renumber(status.nodes_to_com);
status_list.push(partition);
mod = new_mod;
var current_graph = induced_graph(partition, original_graph);
init_status(current_graph, status);
while (true){
__one_level(current_graph, status);
new_mod = __modularity(status);
if(new_mod - mod < __MIN)
break;
partition = __renumber(status.nodes_to_com);
status_list.push(partition);
mod = new_mod;
current_graph = induced_graph(partition, current_graph);
init_status(current_graph, status);
}
return status_list;
}
var core = function(){
var status = {};
var dendogram = generate_dendogram(original_graph, partition_init);
return partition_at_level(dendogram, dendogram.length - 1);
};
core.nodes = function(nds){
if(arguments.length > 0){
original_graph_nodes = nds;
}
return core;
};
core.edges = function(edgs){
if(typeof original_graph_nodes == 'undefined')
throw 'Please provide the graph nodes first!';
if(arguments.length > 0){
original_graph_edges = edgs;
var assoc_mat = make_assoc_mat(edgs);
original_graph = { 'nodes': original_graph_nodes,
'edges': original_graph_edges,
'_assoc_mat': assoc_mat };
}
return core;
};
core.partition_init = function(prttn){
if(arguments.length > 0){
partition_init = prttn;
}
return core;
};
return core;
}
})();
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>
I look into a few answers but I'm not getting any results, I'm trying to fix this issue "Uncaught TypeError: this.getElements is not a function". This part of the code, full code in the link.
var SIDEBAR = new function() {
this.on = function(nameElement){
this.menu = nameElement;
return this;
};
/*more code*/
this.getElements = function() {
/*more code*/
return [];
};
/*more code*/
this.addElements = function() {
var elementsData = this.getElements();
/*more code*/
};
}();
var sid = SIDEBAR.on('test');
sid.load();
Full code: https://jsfiddle.net/e6shbnsu/
The value of this is determined by how a function is called.
this will point to window in setTimeout. Use .bind to have specified values as this context.
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
function inElectron() {
return navigator.userAgent.indexOf("Electron") != -1;
}
var dataManager = {
getItem: function(key, local) {
if (inElectron() || local == 1)
return localStorage.getItem(key);
else
return sessionStorage.getItem(key);
},
setItem: function(key, item, local) {
if (inElectron() || local == 1)
localStorage.setItem(key, item);
else
sessionStorage.setItem(key, item);
}
};
var SIDEBAR = new function() {
this.on = function(nameElement) {
this.menu = nameElement;
return this;
};
this.load = function() {
this.currentElement = 0;
this.refreshElements();
};
this.setAddElementName = function(name) {
this.addElementName = name;
};
this.setNewElementName = function(name) {
this.newElementName = name;
};
this.getElements = function() {
var elementsData = dataManager.getItem(this.getDataKey);
if (typeof elementsData !== 'undefined' && elementsData !== null) {
return JSON.parse(elementsData);
}
return this.getPreloadData();
};
this.setDataKey = function(key) {
this.dataKey = key;
};
this.getDataKey = function() {
if (this.dataKey) {
return this.dataKey;
}
return "SideBar" + this.menu;
};
this.setPreloadData = function(dataArray) {
this.preloadData = dataArray;
};
this.getPreloadData = function() {
if (typeof this.preloadData !== 'undefined' && this.preloadData !== null) {
return this.preloadData;
}
return [];
};
this.getCurrentElement = function() {
var elementsData = getElements;
return elementsData[currentElement];
};
this.refreshElements = function() {
window.setTimeout(function() {
this.clearElements();
}.bind(this), 1);
//outer `this` context is bound to the handler
window.setTimeout(function() {
this.addElements();
}.bind(this), 2);
};
this.deleteElement = function() {
var newArr = [];
var elementsData = this.getElements();
for (var i = 0, l = elementsData.length; i < l; i++) {
if (i != index) {
newArr.push(elementsData[i]);
}
}
dataManager.setItem(this.getDataKey, JSON.stringify(newArr));
};
this.addElements = function() {
var elementsData = this.getElements();
var menuNode = document.getElementById(this.menu);
console.log(elementsData);
for (var i = 0; i < elementsData.length; i++) {
var li = document.createElement("li");
var div = document.createElement("div");
li.value = i;
div.classList.add("list");
var p = document.createElement("p");
p.id = "textBlock";
p.style.display = "inline";
p.setAttribute("contentEditable", false);
p.appendChild(document.createTextNode(elementsData[i].name));
div.appendChild(p);
var obj = getObject();
console.log(obj);
div.onclick = function(e) {
e.stopImmediatePropagation();
if (this.querySelector("#textBlock").contentEditable == "false") {
this.currentElement = this.parentNode.value;
elementsData = this.getElements();
document.getElementById("prompt").innerHTML = elementsData[this.parentNode.value]["data"];
document.querySelector("#wrapper").classList.toggle("toggled");
}
};
var span2 = document.createElement("span");
span2.id = "deleteMode";
span2.classList.add("glyphicon");
span2.classList.add("glyphicon-minus");
span2.onclick = function(e) {
e.stopImmediatePropagation();
deleteItem(this.parentNode.parentNode.value);
window.setTimeout(this.refreshElements, 1);
};
span2.style.display = "none";
div.appendChild(span2);
var span = document.createElement("span");
span.id = "editMode";
span.classList.add("glyphicon");
span.classList.add("glyphicon-pencil");
span.onclick = function(e) {
e.stopImmediatePropagation();
// get href of first anchor in element and change location
for (var j = 0; j < menuNode.length; j++) {
menuNode[j].classList.add("disabled");
}
this.style.display = "none";
this.parentNode.querySelector("#deleteMode").style.display = "";
this.parentNode.classList.add("editableMode");
this.parentNode.classList.remove("disabled");
var textBlock = this.parentNode.querySelector("#textBlock");
textBlock.setAttribute("contentEditable", true);
this.placeCaretAtEnd(textBlock);
textBlock.onkeydown = function(e) {
if (e.keyCode == 13) {
e.stopImmediatePropagation();
var text = this.innerHTML.replace(" ", '');
text = text.replace("<br>", '');
if (text.length > 0) {
this.innerHTML = text;
elementsData[this.parentNode.parentNode.value]['name'] = text;
dataManager.setItem("IFTeleprompterScripts", JSON.stringify(elementsData));
for (var j = 0; j < menuNode.length; j++) {
menuNode[j].classList.remove("disabled");
}
this.parentNode.classList.remove("editableMode");
this.setAttribute("contentEditable", false);
this.parentNode.querySelector("#editMode").style.display = "";
this.parentNode.querySelector("#deleteMode").style.display = "none";
} else {
return false;
}
} else if (e.keyCode == 8) {
if (textBlock.innerHTML.length - 1 === 0) {
textBlock.innerHTML = " ";
}
}
return true;
};
return false;
};
div.appendChild(span);
li.appendChild(div);
scriptsNode.appendChild(li);
}
var li = document.createElement("li");
var div = document.createElement("div");
var span2 = document.createElement("span");
span2.id = "addMode";
span2.classList.add("glyphicon");
span2.classList.add("glyphicon-plus");
div.appendChild(span2);
var p = document.createElement("p");
p.id = "textBlock";
p.style.display = "inline";
p.setAttribute("contentEditable", false);
if (typeof this.addElementName !== 'undefined' && this.addElementName !== null)
p.appendChild(document.createTextNode(" " + this.addElementName));
else
p.appendChild(document.createTextNode(" Add " + this.menu));
div.appendChild(p);
li.onclick = function(e) {
e.stopImmediatePropagation();
var newPushElementName = "New " + this.menu;
if (typeof this.addElementName !== 'undefined' && this.addElementName !== null) {
newPushElementName = this.addElementName;
}
elementsData.push({
"name": newPushElementName,
"data": ""
});
dataManager.setItem(this.getDataKey, JSON.stringify(elementsData));
this.refreshElements();
};
li.appendChild(div);
menuNode.appendChild(li);
};
this.placeCaretAtEnd = function(el) {
el.focus();
if (typeof window.getSelection != "undefined" && typeof document.createRange != "undefined") {
var range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange != "undefined") {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(false);
textRange.select();
}
};
}();
var sid = SIDEBAR.on('test');
sid.load();
<ul class="sidebar-nav" id="test">
</ul>
I found this code on net, it's about a memory game.
var MemoryApp = (function () {
'use strict';
var size = 36;
var sizeStyle = "smallGame";
var maxpics = 18;
var gameRunning = false;
var cardOpen = null;
var time = 0;
var timer;
var s4;
var s6;
var s8;
var attempts = 0;
var found = 0;
var foundDisp;
var attDisp;
var timeDisp;
var template;
var popupImage;
var popupHolder;
var gameGrid;
var currentCardSet = 'zoo';
var currentCards = [];
window.onload = runGame;
function activated() {
WinJS.UI.processAll().then(function(){
s4 = document.getElementById("size4x4");
s6 = document.getElementById("size6x6");
s8 = document.getElementById("size8x8");
s4.addEventListener("click", gameSize, false);
s6.addEventListener("click", gameSize, false);
s8.addEventListener("click", gameSize, false);
var start = document.getElementById("startGame");
if (start) {
start.onclick = runGame;
}
var stop = document.getElementById("stopGame");
if (stop) {
stop.onclick = stopGame;
}
template = document.getElementById("cardTemplate");
popupImage = document.getElementById("popupImage");
popupHolder = document.getElementById("popupHolder");
popupHolder.addEventListener("click", closeImageView, false);
foundDisp = document.getElementById("foundDisplay");
attDisp = document.getElementById("attemptsDisplay");
timeDisp = document.getElementById("timeDisplay");
// Expose functions globally
window.updateClock = updateClock;
window.resetCards = resetCards;
window.gameTag1 = null;
window.gameTag2 = null;
buildCards();
});
}
function closeImageView() {
removeClass(popupHolder, "openImagePopup");
}
function makePictureArray() {
var pics = new Array();
for (var i = 0; i < maxpics; i++) {
pics[i] = getDefaultURL(i);
}
return pics;
}
function removeAllChildren(element) {
if (element.hasChildNodes()) {
while (element.childNodes.length > 0) {
element.removeChild(element.firstChild);
}
}
}
function buildCards() {
// Assumption: game grid size is a power of 2
var stride = Math.sqrt(size);
// Make picture selection
var pics = makePictureArray();
var sel = new Array();
for (var i = 0; i < size / 2; i++) {
var idx = parseInt(Math.random() * pics.length);
sel[i] = pics[idx];
// remove the used pic
pics.splice(idx, 1);
}
// get an array with the card content
var content = new Array();
for (var i = 0; i < size / 2; i++) {
content[i] = sel[i];
content[i + size / 2] = sel[i];
}
var gameBoard = document.querySelector('#gameBoard');
removeAllChildren(gameBoard);
var gameGrid = document.createElement("div");
gameGrid.id = "gameGrid";
addClass(gameGrid, sizeStyle);
gameBoard.appendChild(gameGrid);
for (var i=0; i<size; i++) {
var item = document.createElement("div");
item.className = "gameItem"+i;
item.addEventListener("click", cardClicked, false);
setClosed(item);
var r = parseInt(Math.random() * content.length);
// Add image
insertTemplate(item, template);
var walker = document.createTreeWalker(item, NodeFilter.SHOW_ELEMENT, imgFilter, false);
while (walker.nextNode())
walker.currentNode.setAttribute("src", content[r]);
// Add path to ease styling
var walker = document.createTreeWalker(item, NodeFilter.SHOW_ELEMENT, pFilter, false);
while (walker.nextNode())
walker.currentNode.innerText = content[r];
item.contentIndex = content[r];
content.splice(r, 1);
gameGrid.appendChild(item);
}
}
function imgFilter(node) {
if (node.tagName == "IMG") //filter IMG elements
return NodeFilter.FILTER_ACCEPT
else
return NodeFilter.FILTER_SKIP
}
function pFilter(node) {
if (node.tagName == "P") //filter IMG elements
return NodeFilter.FILTER_ACCEPT
else
return NodeFilter.FILTER_SKIP
}
function insertTemplate(parent, templateParent) {
if (templateParent.children && templateParent.children.length >= 1) {
var tchild = templateParent.children[0].cloneNode(true);
parent.appendChild(tchild);
}
}
function gameSize() {
document.size.size4x4.checked = false;
document.size.size6x6.checked = false;
document.size.size8x8.checked = false;
var newsize = 36;
var gSize = "smallGame";
if (this.name == "size4x4") {
document.size.size4x4.checked = true;
newsize = 36;
gSize = "smallGame";
}
if (this.name == "size6x6") {
document.size.size6x6.checked = true;
newsize = 36;
gSize = "mediumGame";
}
if (this.name == "size8x8") {
document.size.size8x8.checked = true;
newsize = 36;
gSize = "largeGame";
}
if (!gameRunning == true) {
size = newsize;
sizeStyle = gSize;
buildCards();
}
}
function stopGame() {
if (!gameRunning)
return;
gameRunning = false;
foundDisp.innerText = "0";
found = 0;
attDisp.innerText = "0";
attempts = 0;
clearInterval(timer);
timeDisp.innerText = "00:00";
s4.disabled = false;
s6.disabled = false;
s8.disabled = false;
}
function runGame() {
//don't do anything if game already running
if (gameRunning == true)
return;
window.gameTag1 = null;
window.gameTag2 = null;
cardOpen = null;
gameRunning = true;
buildCards();
timeDisp.innerText = "00:00";
time = 0;
foundDisp.innerText = "0";
found = 0;
attDisp.innerText = "0";
attempts = 0;
timer = setInterval("updateClock()", 1000);
s4.disabled = true;
s6.disabled = true;
s8.disabled = true;
}
function getDefaultURL(i) {
var idx = i+1;
if (idx<1)
idx = 1;
if (idx>32)
idx = 32;
var result = "/photos/" + currentCardSet + "/";
if (idx < 10)
result = result + "0";
result = result + idx.toString() + ".jpg";
return result;
}
function updateClock() {
time = time + 1;
var mins = parseInt(time / 60);
var secs = time - mins * 60;
mins = mins.toString();
secs = secs.toString();
if (mins.length < 2)
mins = "0" + mins;
if (secs.length < 2)
secs = "0" + secs;
timeDisp.innerText = mins + ":" + secs;
}
function cardClicked() {
// If an open card is clicked, bring up the full size popup
if (this.cardFoundFlag || cardOpen === this) {
popupImage.setAttribute("src", this.contentIndex);
popupHolder.style.display = "block";
addClass(popupHolder, "openImagePopup");
return;
}
// don't do anything if no game is running, or a move is in play...
if (!gameRunning || window.gameTag1 !=null || window.gameTag2 != null)
return;
if (cardOpen == null) {
setOpen(this);
cardOpen = this;
} else {
if (this.contentIndex == cardOpen.contentIndex) {
setFound(this);
setFound(cardOpen);
this.cardFoundFlag = true;
cardOpen.cardFoundFlag = true;
cardOpen = null;
found++;
foundDisp.innerText = found;
updateAttempts();
if (found == size / 2) {
gameRunning = false;
clearInterval(timer);
foundDisp.innerText = "ALL!";
}
} else {
setOpen(this);
// Hack to get around insulation of these functions
window.gameTag1 = this;
window.gameTag2 = cardOpen;
setTimeout("resetCards()", 1100);
cardOpen = null;
updateAttempts();
}
}
}
function setOpen(el) {
removeClass(el, "closedCard");
addClass(el, "openCard");
}
function setClosed(el) {
removeClass(el, "openCard");
addClass(el, "closedCard");
}
function setFound(el) {
removeClass(el, "openCard");
removeClass(el, "closedCard");
addClass(el, "foundCard");
}
function resetCardStyles(el) {
removeClass(el, "openCard");
removeClass(el, "foundCard");
addClass(el, "closedCard");
}
function updateAttempts() {
attempts++;
attDisp.innerText = attempts;
}
function resetAllCards() {
buildCards();
}
function resetCards() {
setClosed(window.gameTag1);
setClosed(window.gameTag2);
window.gameTag1 = null;
window.gameTag2 = null;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
// Utilities
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
function hasClass(el, className) {
// authors can pass in either an element object or an ID
el = (typeof (el) == 'object') ? el : document.getElementById(el);
// no need to continue if there's no className
if (!el.className) return false;
// iterate through all the classes
var classArray = el.className.split(' ');
for (var i = 0; i < classArray.length; i++) {
if (className == classArray[i]) return true; // found? return true
}
// if we're still here, the class does not exist
return false;
}
function addClass(el, className) {
// authors can pass in either an element object or an ID
el = (typeof (el) == 'object') ? el : document.getElementById(el);
// simply append the className to the string
el.className += ' ' + className;
return;
}
function removeClass(el, className) {
// authors can pass in either an element object or an ID
el = (typeof (el) == 'object') ? el : document.getElementById(el);
// if the class doesn't exist, there's no need to remove it
if (!hasClass(el, className)) return;
// iterate through all the classes
var classArray = el.className.split(' ');
for (var i = 0; i < classArray.length; i++) {
// found it!
if (className == classArray[i]) {
classArray.splice(i, 1); // remove it
i--; // decrement so we don't skip over any future occurences
}
}
// reassign the className
el.className = classArray.join(' ');
return;
}
WinJS.Application.onactivated = function (e) {
if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
activated();
}
}
WinJS.Application.start();
});
var theMemoryApp = new MemoryApp();
I need to add a function which is going to check for touch or click detection on the screen. If there is no touch after some seconds, all game has to restart from the beginning. How can I do that?
I hide that start and stop buttons on the design. So with window.onload=runGame game starts automatically when its loaded. But need to be restart if children live the game play when its not finished. For example, if there is no touch after 120 seconds, all code has to restart from beginning. Or there is buildCard function in the code. This timer can trigger this function also. I will be glad for any kind of help cause this is for kids.
You can use debounce technique like shown in below snippet. I have added click event but you can add touch specific events also. timer() will be triggered every 120 secs if click event is not triggered i.e if user doesn't click or touch. I could not run your code to test. Please let me know if this doesn't work.
var MemoryApp = (function () {
'use strict';
var size = 36;
var sizeStyle = "smallGame";
var maxpics = 18;
var gameRunning = false;
var cardOpen = null;
var time = 0;
var timer;
var s4;
var s6;
var s8;
var attempts = 0;
var found = 0;
var foundDisp;
var attDisp;
var timeDisp;
var template;
var popupImage;
var popupHolder;
var gameGrid;
var currentCardSet = 'zoo';
var currentCards = [],
__timeOut = 0;
window.onload = runGame;
var timer = function() {
clearTimeout(__timeOut);
__timeOut = setTimeout(function() {
buildCards();
}, 120000);
};
window.addEventListener('click', timer);
function activated() {
WinJS.UI.processAll().then(function(){
s4 = document.getElementById("size4x4");
s6 = document.getElementById("size6x6");
s8 = document.getElementById("size8x8");
s4.addEventListener("click", gameSize, false);
s6.addEventListener("click", gameSize, false);
s8.addEventListener("click", gameSize, false);
var start = document.getElementById("startGame");
if (start) {
start.onclick = runGame;
}
var stop = document.getElementById("stopGame");
if (stop) {
stop.onclick = stopGame;
}
template = document.getElementById("cardTemplate");
popupImage = document.getElementById("popupImage");
popupHolder = document.getElementById("popupHolder");
popupHolder.addEventListener("click", closeImageView, false);
foundDisp = document.getElementById("foundDisplay");
attDisp = document.getElementById("attemptsDisplay");
timeDisp = document.getElementById("timeDisplay");
// Expose functions globally
window.updateClock = updateClock;
window.resetCards = resetCards;
window.gameTag1 = null;
window.gameTag2 = null;
buildCards();
});
}
function closeImageView() {
removeClass(popupHolder, "openImagePopup");
}
function makePictureArray() {
var pics = new Array();
for (var i = 0; i < maxpics; i++) {
pics[i] = getDefaultURL(i);
}
return pics;
}
function removeAllChildren(element) {
if (element.hasChildNodes()) {
while (element.childNodes.length > 0) {
element.removeChild(element.firstChild);
}
}
}
function buildCards() {
// Assumption: game grid size is a power of 2
var stride = Math.sqrt(size);
// Make picture selection
var pics = makePictureArray();
var sel = new Array();
for (var i = 0; i < size / 2; i++) {
var idx = parseInt(Math.random() * pics.length);
sel[i] = pics[idx];
// remove the used pic
pics.splice(idx, 1);
}
// get an array with the card content
var content = new Array();
for (var i = 0; i < size / 2; i++) {
content[i] = sel[i];
content[i + size / 2] = sel[i];
}
var gameBoard = document.querySelector('#gameBoard');
removeAllChildren(gameBoard);
var gameGrid = document.createElement("div");
gameGrid.id = "gameGrid";
addClass(gameGrid, sizeStyle);
gameBoard.appendChild(gameGrid);
for (var i=0; i<size; i++) {
var item = document.createElement("div");
item.className = "gameItem"+i;
item.addEventListener("click", cardClicked, false);
setClosed(item);
var r = parseInt(Math.random() * content.length);
// Add image
insertTemplate(item, template);
var walker = document.createTreeWalker(item, NodeFilter.SHOW_ELEMENT, imgFilter, false);
while (walker.nextNode())
walker.currentNode.setAttribute("src", content[r]);
// Add path to ease styling
var walker = document.createTreeWalker(item, NodeFilter.SHOW_ELEMENT, pFilter, false);
while (walker.nextNode())
walker.currentNode.innerText = content[r];
item.contentIndex = content[r];
content.splice(r, 1);
gameGrid.appendChild(item);
}
}
function imgFilter(node) {
if (node.tagName == "IMG") //filter IMG elements
return NodeFilter.FILTER_ACCEPT
else
return NodeFilter.FILTER_SKIP
}
function pFilter(node) {
if (node.tagName == "P") //filter IMG elements
return NodeFilter.FILTER_ACCEPT
else
return NodeFilter.FILTER_SKIP
}
function insertTemplate(parent, templateParent) {
if (templateParent.children && templateParent.children.length >= 1) {
var tchild = templateParent.children[0].cloneNode(true);
parent.appendChild(tchild);
}
}
function gameSize() {
document.size.size4x4.checked = false;
document.size.size6x6.checked = false;
document.size.size8x8.checked = false;
var newsize = 36;
var gSize = "smallGame";
if (this.name == "size4x4") {
document.size.size4x4.checked = true;
newsize = 36;
gSize = "smallGame";
}
if (this.name == "size6x6") {
document.size.size6x6.checked = true;
newsize = 36;
gSize = "mediumGame";
}
if (this.name == "size8x8") {
document.size.size8x8.checked = true;
newsize = 36;
gSize = "largeGame";
}
if (!gameRunning == true) {
size = newsize;
sizeStyle = gSize;
buildCards();
}
}
function stopGame() {
if (!gameRunning)
return;
gameRunning = false;
foundDisp.innerText = "0";
found = 0;
attDisp.innerText = "0";
attempts = 0;
clearInterval(timer);
timeDisp.innerText = "00:00";
s4.disabled = false;
s6.disabled = false;
s8.disabled = false;
}
function runGame() {
//don't do anything if game already running
if (gameRunning == true)
return;
window.gameTag1 = null;
window.gameTag2 = null;
cardOpen = null;
gameRunning = true;
buildCards();
timeDisp.innerText = "00:00";
time = 0;
foundDisp.innerText = "0";
found = 0;
attDisp.innerText = "0";
attempts = 0;
timer = setInterval("updateClock()", 1000);
s4.disabled = true;
s6.disabled = true;
s8.disabled = true;
}
function getDefaultURL(i) {
var idx = i+1;
if (idx<1)
idx = 1;
if (idx>32)
idx = 32;
var result = "/photos/" + currentCardSet + "/";
if (idx < 10)
result = result + "0";
result = result + idx.toString() + ".jpg";
return result;
}
function updateClock() {
time = time + 1;
var mins = parseInt(time / 60);
var secs = time - mins * 60;
mins = mins.toString();
secs = secs.toString();
if (mins.length < 2)
mins = "0" + mins;
if (secs.length < 2)
secs = "0" + secs;
timeDisp.innerText = mins + ":" + secs;
}
function cardClicked() {
// If an open card is clicked, bring up the full size popup
if (this.cardFoundFlag || cardOpen === this) {
popupImage.setAttribute("src", this.contentIndex);
popupHolder.style.display = "block";
addClass(popupHolder, "openImagePopup");
return;
}
// don't do anything if no game is running, or a move is in play...
if (!gameRunning || window.gameTag1 !=null || window.gameTag2 != null)
return;
if (cardOpen == null) {
setOpen(this);
cardOpen = this;
} else {
if (this.contentIndex == cardOpen.contentIndex) {
setFound(this);
setFound(cardOpen);
this.cardFoundFlag = true;
cardOpen.cardFoundFlag = true;
cardOpen = null;
found++;
foundDisp.innerText = found;
updateAttempts();
if (found == size / 2) {
gameRunning = false;
clearInterval(timer);
foundDisp.innerText = "ALL!";
}
} else {
setOpen(this);
// Hack to get around insulation of these functions
window.gameTag1 = this;
window.gameTag2 = cardOpen;
setTimeout("resetCards()", 1100);
cardOpen = null;
updateAttempts();
}
}
}
function setOpen(el) {
removeClass(el, "closedCard");
addClass(el, "openCard");
}
function setClosed(el) {
removeClass(el, "openCard");
addClass(el, "closedCard");
}
function setFound(el) {
removeClass(el, "openCard");
removeClass(el, "closedCard");
addClass(el, "foundCard");
}
function resetCardStyles(el) {
removeClass(el, "openCard");
removeClass(el, "foundCard");
addClass(el, "closedCard");
}
function updateAttempts() {
attempts++;
attDisp.innerText = attempts;
}
function resetAllCards() {
buildCards();
}
function resetCards() {
setClosed(window.gameTag1);
setClosed(window.gameTag2);
window.gameTag1 = null;
window.gameTag2 = null;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
// Utilities
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
function hasClass(el, className) {
// authors can pass in either an element object or an ID
el = (typeof (el) == 'object') ? el : document.getElementById(el);
// no need to continue if there's no className
if (!el.className) return false;
// iterate through all the classes
var classArray = el.className.split(' ');
for (var i = 0; i < classArray.length; i++) {
if (className == classArray[i]) return true; // found? return true
}
// if we're still here, the class does not exist
return false;
}
function addClass(el, className) {
// authors can pass in either an element object or an ID
el = (typeof (el) == 'object') ? el : document.getElementById(el);
// simply append the className to the string
el.className += ' ' + className;
return;
}
function removeClass(el, className) {
// authors can pass in either an element object or an ID
el = (typeof (el) == 'object') ? el : document.getElementById(el);
// if the class doesn't exist, there's no need to remove it
if (!hasClass(el, className)) return;
// iterate through all the classes
var classArray = el.className.split(' ');
for (var i = 0; i < classArray.length; i++) {
// found it!
if (className == classArray[i]) {
classArray.splice(i, 1); // remove it
i--; // decrement so we don't skip over any future occurences
}
}
// reassign the className
el.className = classArray.join(' ');
return;
}
WinJS.Application.onactivated = function (e) {
if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
activated();
}
}
WinJS.Application.start();
});
var theMemoryApp = new MemoryApp();
I am trying to find a specific class (profileCard) and then check if that class has a different class (followStatus) inside it. If it does have followStatus inside it, I want to click a button which is also inside the profileCard class. here is my code:
var profileCard = document.getElementsByClassName('ProfileCard');
var unfollowButtons = profileCard.getElementsByClassName('button-text');
var followStatus = profileCard.getElementsByClassName('FollowStatus');
for (var i = 0; i < profileCard.length; i++) {
if (followStatus[i] != null) {
unfollowButtons[i].click();
}
}
I want to use this function in Chrome simply pasting it into the console, but the code seemingly does nothing: the button is never clicked. Where is the error in my code and how can I fix that?
It's more convenient to use querySelector method here inside the loop over .profileCards elements:
var profileCards = document.querySelectorAll('.ProfileCard');
for (var i = 0; i < profileCards.length; i++) {
if (profileCards[i].querySelector('.FollowStatus')) {
var button = profileCards[i].querySelector('.button-text');
if (button) {
button.click();
}
}
}
Well i suggest programming some sort of Node selector or using http://jquery.com/.
Please note document.getElementsByClass name is not compatible in some browsers.
Here is a node selector i just programmed which solves that.
N$ = (function(){
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(elt /*, from*/)
{
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++)
{
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
if (!window.getComputedStyle) {//IE
window.getComputedStyle = function(el, pseudo) {
this.el = el;
this.getPropertyValue = function(prop) {
var re = /(\-([a-z]){1})/g;
if (prop == 'float') prop = 'styleFloat';
if (re.test(prop)) {
prop = prop.replace(re, function () {
return arguments[2].toUpperCase();
});
}
return el.currentStyle[prop] ? el.currentStyle[prop] : null;
}
return this;
}
}
var N$_CURRENT_EVENT_THIS = null;
var DOM_N$ = function(selector){
if(typeof selector == typeof ""){
this.selector = selector;
this.nodes = $prepare(this.selector);
this.win = window;
this.doc = document;
}else if(typeof selector == typeof {}){
this.selector = N$_CURRENT_EVENT_THIS.selector;
this.nodes = $prepare(this.selector);
this.win = window;
this.doc = document;
}
this.getSelector=function(){
return this.selector;
};
this.eachNode = function(func){
var that = this;
for (var i = 0; i < this.nodes.length; i++) {
N$_CURRENT_EVENT_THIS = that;
func(this.nodes[i]);
N$_CURRENT_EVENT_THIS = null;
};
};
this.css = function(attr, value){
N$_CURRENT_EVENT_THIS = this;
var attribute = "";
if(attr.indexOf('-') !== -1){
var split_attr = attr.split('-');
for (var i = 0; i < split_attr.length; i++) {
if(i != 0)
attribute += split_attr[i].charAt(0).toUpperCase() + split_attr[i].slice(1);
else
attribute += split_attr[i].charAt(0).toLowerCase() + split_attr[i].slice(1);
};
}else{
attribute = attr;
}
var properties = new Array();
for (var i = 0; i < this.nodes.length; i++) {
if(typeof value != 'undefined'){
this.nodes[i].style[attribute] = value;
}
properties.push(window.getComputedStyle(this.nodes[i], null).getPropertyValue(attr));
};
return properties;
};
this.addEvent = function(event_, func){
var that = this;
for (var i = 0; i < this.nodes.length; i++) {
var node = this.nodes[i];
var events = this.nodes[i].events || {};
if(node.addEventListener){
if((event_) in events){
node.removeEventListener(event_, events[event_], true);
var tmp___ = events[event_];
var tmp__ = function(){
this.bar = "hello";
N$_CURRENT_EVENT_THIS = that;
tmp___(node, event_);
func(node, event_);
N$_CURRENT_EVENT_THIS = null;
};
node.addEventListener(event_, tmp__, true);
events[event_] = tmp__;
}else{
var tmp__ = function(){
N$_CURRENT_EVENT_THIS = that;
func(node, event_);
N$_CURRENT_EVENT_THIS = null;
};
node.addEventListener(event_, tmp__, true);
events[event_] = tmp__;
}
}else if(node.attachEvent){
var ie_event = 'on' + event_;
if(event_ in events){
node.attachEvent(ie_event, function(){
N$_CURRENT_EVENT_THIS = that;
func(node, event_);
events[event_](node, event_);
N$_CURRENT_EVENT_THIS = null;
});
}else{
node.attachEvent(ie_event, function(){
N$_CURRENT_EVENT_THIS = that;
func(node, event_);
N$_CURRENT_EVENT_THIS = null;
});
}
events[event_] = func;
}
this.nodes[i].events = events;
}
};
this.removeEvent = function(event_){
N$_CURRENT_EVENT_THIS = this;
for (var i = 0; i < this.nodes.length; i++) {
var node = this.nodes[i];
var events = this.nodes[i].events || {};
if(node.removeEventListener){
if((event_) in events){
node.removeEventListener(event_, events[event_], true);
events[event_] = null;
}
}else if(node.detachEvent){
var ie_event = 'on' + event_;
if((event_) in events){
node.detachEvent(ie_event, events[event_]);
delete events[event_];
}
}
}
};
this.text = function(str){
N$_CURRENT_EVENT_THIS = this;
for (var i = 0; i < this.nodes.length; i++) {
var node = this.nodes[i];
node.innerHTML = '';
node.appendChild(document.createTextNode(str));
}
};
this.animate = function(func, from, to, speed){
var nodes = this.nodes;
var that = this;
for (var i = 0; i < this.nodes.length; i++) {
(function animate(func, from, to, speed, i){
if(from >= to){
N$_CURRENT_EVENT_THIS = that;
func(nodes[i], to);
N$_CURRENT_EVENT_THIS = null;
}else{
N$_CURRENT_EVENT_THIS = that;
func(nodes[i], from);
N$_CURRENT_EVENT_THIS = null;
setTimeout(
function(){
animate(func, from +1, to, speed, i);
}, speed
);
}
})(func, from, to, speed, i);
}
};
this.appendNode = function(tagname, innerHTML){
for (var i = 0; i < this.nodes.length; i++) {
var new_node = document.createElement(tagname);
new_node.innerHTML = innerHTML;
this.nodes[i].appendChild(new_node);
}
};
this.removeNode = function(){
for (var i = 0; i < this.nodes.length; i++) {
this.nodes[i].parentNode.removeChild(this.nodes[i]);
}
};
function $prepare(str){
str = str.replace(/(\s+>\s+)/g,'>');
str = str.replace(/(\s+)/g,' ');
var str_ = str;
var querys = str.split(/[\s\>]+/);
var querys_des = Array();
var ascender = new Array();
for (var i = 0; i < str_.length; i++) {
if(str_[i] == ">" || str_[i] == " "){
var tmp_ = (str_[i] == ">")? 'next_child' : 'ascended';
ascender.push( tmp_);
}
};
var recognizes = new Array();
for (var i = 0; i < querys.length; i++) {
var asc_child = null;
asc_child = ascender[i-1];
var tmp_ = {
"selector": querys[i],
"i":i
};
recognizes[i] = recognize(querys[i]);
if(i != 0){
tmp_["asc_child"] = asc_child;
}else{
tmp_["base_selector"] = true;
}
querys_des.push(tmp_);
};
return $select(querys_des, recognizes);
}
function $select(querys_des, recognizes, parent_){
var parents = parent_ || null;
for (var i = 0; i < querys_des.length; i++) {
if('base_selector' in querys_des[i]){
parents = recognizes[querys_des[i]['i']];
}else if('asc_child' in querys_des[i]){
var cur_children = recognizes[querys_des[i]['i']];
if(querys_des[i]['asc_child'] == 'next_child'){
var compatible = compatible_children(parents, cur_children, querys_des[i]['asc_child']);
parents = compatible;
}else if(querys_des[i]['asc_child'] == 'ascended'){
var compatible = compatible_children(parents, cur_children, querys_des[i]['asc_child']);
parents = compatible;
}
}
};
return parents;
}
function compatible_children(parents, children, type){
var ret = new Array();
for (var a = 0; a < parents.length; a++) {
for (var b = 0; b < children.length; b++) {
if(type == 'next_child'){
if(parents[a] == children[b].parentNode){
if(ret.indexOf(children[b]) == -1)
ret.push(children[b]);
}
}else if(type == 'ascended'){
if(isin(parents[a], children[b])){
if(ret.indexOf(children[b]) == -1)
ret.push(children[b]);
}
}
}
}
return ret;
}
function isin(parent, child){
var child_ = child;
var ret = new Array();
while((child_ = child_.parentNode) && child_ != document.body){
if(parent == child_){
return true;
}
}
return false;
}
function recognize(str){
var identifier = new Array();
var id_ = false;
var class_ = false;
var dom_ = false;
if(str.indexOf("#") >= 0){
id_ = true;
var tmp = str.split("#")[1];
if(str.indexOf(".") >= 0){
identifier['ID'] = tmp.split(".")[0];
}else{
identifier['ID'] = tmp;
}
}
if(str.indexOf(".") >= 0){
class_ = true;
var tmp = str.split(".")[1];
if(str.indexOf("#") >= 0){
identifier['CLASS'] = tmp.split("#")[0];
}else{
identifier['CLASS'] = tmp;
}
}
if(id_ && class_){
if(str.indexOf("#") < str.indexOf(".")){
var tmp = str.split("#")[0];
if(tmp.length > 0){
dom_ = true;
identifier['DOM'] = tmp;
}
}else{
var tmp = str.split(".")[0];
if(tmp.length > 0){
dom_ = true;
identifier['DOM'] = tmp;
}
}
}else if(id_){
var tmp = str.split("#")[0];
if(tmp.length > 0){
dom_ = true;
identifier['DOM'] = tmp;
}
}else if(class_){
var tmp = str.split(".")[0];
if(tmp.length > 0){
dom_ = true;
identifier['DOM'] = tmp;
}
}else{
if(str.length > 0){
dom_ = true;
identifier['DOM'] = str;
}
}
var x;
if(class_){
if(typeof document.getElementsByClassName !== 'function') {//Old browsers
x = document.body.getElementsByTagName("*");
}else{
x = document.getElementsByClassName(identifier['CLASS']);
}
}else if(dom_){
x = document.getElementsByTagName(identifier['DOM']);
}else if(id_){
x = document.body.getElementsByTagName("*");
for (var i = 0; i < x.length; i++) {
if(x[i].getAttribute("id") != identifier['ID']){
delete x[i];
}
};
}
var elements = new Array();
for (var i = 0; i < x.length; i++) {
if(id_ && class_){
if(x[i].getAttribute("id") == identifier["ID"] && x[i].getAttribute("class") == identifier["CLASS"]){
if(dom_){
if(x[i].tagName.toLowerCase() == identifier['DOM'].toLowerCase()){
elements.push(x[i]);
}
}else{
elements.push(x[i]);
}
}
}else if(id_){
if(x[i].getAttribute("id") == identifier["ID"]){
if(dom_){
if(x[i].tagName.toLowerCase() == identifier['DOM'].toLowerCase()){
elements.push(x[i]);
}
}else{
elements.push(x[i]);
}
}
}else if(class_){
if(x[i].getAttribute("class") == identifier["CLASS"]){
if(dom_){
if(x[i].tagName.toLowerCase() == identifier['DOM'].toLowerCase()){
elements.push(x[i]);
}
}else{
elements.push(x[i]);
}
}
}else{
if(dom_){
if(x[i].tagName.toLowerCase() == identifier['DOM'].toLowerCase()){
elements.push(x[i]);
}
}else{
elements.push(x[i]);
}
}
};
return elements;
}
}
var selectors = new Array();
return function(selector){
var N$_new = new DOM_N$(selector);
var N$_ = null;
if(selectors.length > 0){
for (var i = selectors.length - 1; i >= 0; i--) {
if(selectors[i].selector == selector){
var not_in = new Array();
for (var b = N$_new.nodes.length - 1; b >= 0; b--) {
if(selectors[i].nodes.indexOf(N$_new.nodes[b]) == -1){
not_in.push(N$_new.nodes[b]);
}
};
for (var a = not_in.length - 1; a >= 0; a--) {
if(selectors[i].nodes.indexOf(not_in[a]) == -1){
selectors[i].nodes.push(not_in[a]);
}
};
N$_ = selectors[i];
break;
}else{
N$_ = N$_new;
/*
if(N$_.nodes.length > 0){
selectors.push(N$_);
}*/
}
};
}else{
N$_ = N$_new;
if(N$_.nodes.length > 0){
selectors.push(N$_);
}
}
return N$_;
};
})();
use with:
N$('.ProfileCard .FollowStatus').addEvent('click', function(node_, event_){
//Do something.
//node_ is a native Node
});