Find a class inside another class and do some browser action - javascript

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
});

Related

Simplify if else statements through a Javascript Array

I have written some javascript code for a multilanguage site. The code works great but I feel like I have a lot of duplicate code. I was wondering if someone can explain how I can make this simpler or minimized. I have tried to use a forEach(function (item, index) but it does not seem to be working.
This is the original code that works....
(function () {
var lang1 = "/en/"; //default language
var lang2 = "/fr/"; //second language
var lang3 = "/es/"; //third language
var languageSwitcher = document.querySelectorAll("a[href='/languages']").forEach((el) => el.parentNode.classList.add("language-switcher"));
document.querySelector("[data-folder='/languages']").classList.add("language-switcher");
document.querySelectorAll(".language-switcher .header-nav-folder-item").forEach((el) => el.classList.add("languages"));
document.querySelectorAll(".language-switcher .header-menu-nav-item:not(:first-child)").forEach((el) => el.classList.add("languages"));
var languages = document.querySelectorAll(".languages");
var language1 = document.querySelectorAll(".language-switcher .languages a[href*='"+lang1+"']");
var language2 = document.querySelectorAll(".language-switcher .languages a[href*='"+lang2+"']")
var language3 = document.querySelectorAll(".language-switcher .languages a[href*='"+lang3+"']")
var windowURL = window.location.href;
var pageURL = windowURL.split("/")[4];
if (pageURL == undefined) {
for (var i = 0; i < language1.length; i++) {
language1[i].onclick = function () {
var path = lang1 + "home";
this.href = path;
};
}
for (var i = 0; i < language2.length; i++) {
language2[i].onclick = function () {
var path = lang2 + "home";
this.href = path;
};
}
for (var i = 0; i < language3.length; i++) {
language3[i].onclick = function () {
var path = lang3 + "home";
this.href = path;
};
}
} else {
for (var i = 0; i < language1.length; i++) {
language1[i].onclick = function () {
var path = lang1 + pageURL;
this.href = path;
};
}
for (var i = 0; i < language2.length; i++) {
language2[i].onclick = function () {
var path = lang2 + pageURL;
this.href = path;
};
}
for (var i = 0; i < language3.length; i++) {
language3[i].onclick = function () {
var path = lang3 + pageURL;
this.href = path;
};
}
}
document.querySelectorAll(".header-nav-item:not(.language-switcher) a").forEach((el) => el.classList.add("language"));
document.querySelectorAll(".header-menu-nav-item:not(.language-switcher) a").forEach((el) => el.classList.add("language"));
document.querySelectorAll('[data-folder="/languages"] .header-menu-nav-item a').forEach((el) => el.classList.remove("language"));
var languageLinks = document.querySelectorAll(".language");
for (var i = 0; i < languageLinks.length; i++) {
var navURL = languageLinks[i].href;
if (windowURL.indexOf(lang1) != -1) {
languages.forEach((el) => el.classList.remove("active"));
languages[0].classList.add("active");
if (navURL.indexOf(lang1) != -1) {
languageLinks[i].closest("div").style.display = "block";
} else {
languageLinks[i].closest("div").style.display = "none";
}
} else if (windowURL.indexOf(lang2) != -1) {
languages.forEach((el) => el.classList.remove("active"));
languages[1].classList.add("active");
if (navURL.indexOf(lang2) != -1) {
languageLinks[i].closest("div").style.display = "block";
} else {
languageLinks[i].closest("div").style.display = "none";
}
} else if (windowURL.indexOf(lang3) != -1) {
if (navURL.indexOf(lang3) != -1) {
languages.forEach((el) => el.classList.remove("active"));
languages[2].classList.add("active");
languageLinks[i].closest("div").style.display = "block";
} else {
languageLinks[i].closest("div").style.display = "none";
}
} else {
if (navURL.indexOf(lang1) != -1) {
languages.forEach((el) => el.classList.remove("active"));
languages[0].classList.add("active");
languageLinks[i].closest("div").style.display = "block";
} else {
languageLinks[i].closest("div").style.display = "none";
}
}
}
var active = document.querySelector(".language-switcher .active");
active.closest(".language-switcher").prepend(active);
document.querySelectorAll(".header a").forEach((el) => (el.style.visibility = "visible"));
languageSwitcher.style.display = "flex";
})();
I have attempted to use a forEach function and an array but it is not working.
(function () {
var lang = ["/en/", "/fr/", "/es/"];
document.querySelectorAll("a[href='/languages']").forEach((el) => el.parentNode.classList.add("language-switcher"));
document.querySelector("[data-folder='/languages']").classList.add("language-switcher");
document.querySelectorAll(".language-switcher .header-nav-folder-item").forEach((el) => el.classList.add("languages"));
document.querySelectorAll(".language-switcher .header-menu-nav-item:not(:first-child)").forEach((el) => el.classList.add("languages"));
var languages = document.querySelectorAll(".languages");
var windowURL = window.location.href;
var pageURL = windowURL.split("/")[4];
lang.forEach(function (index, value) {
var language = document.querySelectorAll(".language-switcher .languages a[href*='" + value + "']");
if (pageURL == undefined) {
for (var i = 0; i < language.length; i++) {
language[i].onclick = function () {
var path = value + "home";
this.href = path;
};
}
} else {
for (var i = 0; i < language.length; i++) {
language[i].onclick = function () {
var path = value + pageURL;
this.href = path;
};
}
}
document.querySelectorAll(".header-nav-item:not(.language-switcher) a").forEach((el) => el.classList.add("language"));
document.querySelectorAll(".header-menu-nav-item:not(.language-switcher) a").forEach((el) => el.classList.add("language"));
document.querySelectorAll('[data-folder="/languages"] .header-menu-nav-item a').forEach((el) => el.classList.remove("language"));
var languageLinks = document.querySelectorAll(".language");
for (var j = 0; j < languageLinks.length; j++) {
var navURL = languageLinks[j].href;
if (windowURL.indexOf(value) != -1) {
languages.forEach((el) => el.classList.remove("active"));
languages[index].classList.add("active");
if (navURL.indexOf(value) != -1) {
languageLinks[j].closest("div").style.display = "block";
} else {
languageLinks[j].closest("div").style.display = "none";
}
} else {
if (navURL.indexOf('/en/') != -1) {
languages.forEach((el) => el.classList.remove("active"));
languages[0].classList.add("active");
languageLinks[j].closest("div").style.display = "block";
} else {
languageLinks[j].closest("div").style.display = "none";
}
}
}
document.querySelector(".header").style.visibility = "visible";
var active = document.querySelector(".language-switcher .active");
active.closest(".language-switcher").prepend(active);
});
})();

I'm getting this error Uncaught TypeError: this.getElements is not a function

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>

Restart a function if there is no click, or touch event on screen

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();

call function without parenthesis

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

Using photoswipe run a iframe video in lightbox

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

Categories