How to refactor my autocomplete application - javascript

I've written a sample autocomplete application that works as I intended.
HTML
<div class="wrapper">
<div class="search">
<input type="text" id="search" placeholder="Search" onkeyup="autoComplete(this.value)">
<button onclick="search()">Go</button>
<ul id="suggest">
</ul>
</div>
<div class="result">
</div>
</div>
Script
var data = ['Bob', 'Aria', 'Smith', 'Jack', 'Cethy', 'Brad', 'Jony', 'Dan', 'Ashley', 'Janice'];
var suggestionArray = [];
var search = function(){
var searchTerm = document.getElementById('search').value;
if(searchTerm == undefined || searchTerm == ""){
return false;
}
console.log('You are searching for ' + searchTerm);
}
var clearSuggestion = function() {
suggestionArray = [];
}
var addListenersToChild = function(){
var el = document.getElementById('suggest');
el.addEventListener('click', function(event){
var searchTerm = event.target.textContent;
document.getElementById('search').value = searchTerm;
clearSuggestion();
showSuggestion();
}, false)
}
var showSuggestion = function(){
var el = document.getElementById('suggest');
el.innerHTML = "";
if(suggestionArray.length>0){
suggestionArray.forEach(function(suggestTerm){
var node = document.createElement('li');
var textnode = document.createTextNode(suggestTerm);
node.appendChild(textnode);
el.appendChild(node);
});
addListenersToChild();
}
}
var formSuggestionArray = function(dataTerm){
if(suggestionArray.indexOf(dataTerm) > -1){
return false;
} else {
suggestionArray.push(dataTerm);
}
}
var matchVal = function(val){
clearSuggestion();
for(var i=0; i<data.length;i++){
if(data[i].toLowerCase().indexOf(val.toLowerCase()) > -1) {
formSuggestionArray(data[i]);
}
}
}
var autoComplete = function(val){
if(val == undefined || val == ""){
clearSuggestion();
showSuggestion();
return false;
}
matchVal(val);
showSuggestion();
}
I am not sure, if the way I've written the code is the best way to do so. So for example, what I need to know is that if my current program is
good for readability
is optimized
follows the best practices or not
How can I improve the code

Looks GREAT to me, however...
var data = ['Bob', 'Aria', 'Smith', 'Jack', 'Cethy', 'Brad', 'Jony', 'Dan', 'Ashley', 'Janice'];
var suggestionArray = [];
/* Caching these two element nodes speeds things up a bit.. */
var search_element = document.getElementById('search');
var suggestion_element = document.getElementById('suggest');
var search = function(){
var searchTerm = search_element.value;
// concise falsey, TRUE IF `searchTerm` == 0 || undefined || ""
if(!searchTerm){
return false;
}
console.log('You are searching for ' + searchTerm);
}
/*
plurize because contains multiple values,
optionally can just do `suggestionArray.length = 0` equivalent
*/
var clearSuggestions = function() {
suggestionArray = [];
}
var addListenersToChild = function(){
suggestion_element.addEventListener('click', function(event){
var searchTerm = event.target.textContent;
search_element.value = searchTerm;
clearSuggestions();
showSuggestion();
}, false)
}
var showSuggestion = function(){
suggestion_element.innerHTML = "";
/* implicit casting/coersion - IF length == 0 (false) ELSE (true) */
if(suggestionArray.length){
/* reuse this `node` variable */
var node;
suggestionArray.forEach(function(suggestTerm){
node = document.createElement('li');
node.textContent = suggestTerm;
/*
too verbose/unnecessary in my opinion
var textnode = document.createTextNode(suggestTerm);
node.appendChild(textnode);
*/
suggestion_element.appendChild(node);
});
addListenersToChild();
}
}
var formSuggestionArray = function(dataTerm){
/* you can use a native `Set` for `suggestionArray`, insures unique entries */
if(suggestionArray.indexOf(dataTerm) > -1){
return false;
} else {
suggestionArray.push(dataTerm);
}
}
var matchVal = function(val){
clearSuggestions();
for(var i=0; i<data.length;i++){
if(data[i].toLowerCase().indexOf(val.toLowerCase()) > -1) {
formSuggestionArray(data[i]);
}
}
}
var autoComplete = function(val){
// concise falsey, TRUE IF `val` == 0 || undefined || ""
if(!val){
clearSuggestions();
showSuggestion();
return false;
}
matchVal(val);
showSuggestion();
}

Related

Linkedin Autoconnect With User role

I am trying to fix this script to automatically connect people you may know on Linkedin based on User roles (CEO e.t.c), Can someone help me fix this, Below is my code; I have tried the script on almost all browsers, Somebody help fix this.
var userRole = [
"CEO",
"CIO"
];
var inviter = {} || inviter;
inviter.userList = [];
inviter.className = 'button-secondary-small';
inviter.refresh = function () {
window.scrollTo(0, document.body.scrollHeight);
window.scrollTo(document.body.scrollHeight, 0);
window.scrollTo(0, document.body.scrollHeight);
};
inviter.initiate = function()
{
inviter.refresh();
var connectBtns = $(".button-secondary-small:visible");
//
if (connectBtns == null) {var connectBtns = inviter.initiate();}
return connectBtns;
};
inviter.invite = function () {
var connectBtns = inviter.initiate();
var buttonLength = connectBtns.length;
for (var i = 0; i < buttonLength; i++) {
if (connectBtns != null && connectBtns[i] != null) {inviter.handleRepeat(connectBtns[i]);}
//if there is a connect button and there is at least one that has not been pushed, repeat
if (i == buttonLength - 1) {
console.log("done: " + i);
inviter.refresh();
}
}
};
inviter.handleRepeat = function(button)
{
var nameValue = button.children[1].textContent
var name = nameValue.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
function hasRole(role){
for(var i = 0; i < role.length; i++) {
// cannot read children of undefined
var position = button.parentNode.parentNode.children[1].children[1].children[0].children[3].textContent;
var formatedPosition = position.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
var hasRole = formatedPosition.indexOf(role[i]) == -1 ? false : true;
console.log('Has role: ' + role[i] + ' -> ' + hasRole);
if (hasRole) {
return hasRole;
}
}
return false;
}
if(inviter.arrayContains(name))
{
console.log("canceled");
var cancel = button.parentNode.parentNode.children[0];
cancel.click();
}
else if (hasRole(userRole) == false) {
console.log("cancel");
var cancel = button.parentNode.parentNode.children[0];
cancel.click();
}
else if (button.textContent.indexOf("Connect")<0){
console.log("skipped");
inviter.userList.push(name); // it's likely that this person didn't join linkedin in the meantime, so we'll ignore them
var cancel = button.parentNode.parentNode.children[0];
cancel.click();
}
else {
console.log("added");
inviter.userList.push(name);
button.click();
}
};
inviter.arrayContains = function(item)
{
return (inviter.userList.indexOf(item) > -1);
};
inviter.usersJson = {};
inviter.loadResult = function()
{
var retrievedObject = localStorage.getItem('inviterList');
var temp = JSON.stringify(retrievedObject);
inviter.userList = JSON.parse(temp);
};
inviter.saveResult = function()
{
inviter.usersJson = JSON.stringify(inviter.userList);
localStorage.setItem('inviterList', inviter.usersJson);
};
setInterval(function () { inviter.invite(); }, 5000);
`
When I try executing this, I get the following error:
VM288:49 Uncaught TypeError: Cannot read property 'children' of undefined
at hasRole (<anonymous>:49:71)
at Object.inviter.handleRepeat (<anonymous>:66:11)
at Object.inviter.invite (<anonymous>:30:69)
at <anonymous>:108:35
Any ideas as to how to fix it?

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>

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

Onblur returns wrong data

My form check does not work. If I leave alias field empty it returns name field as filled.
var alias = document.getElementById("alias");
var name = document.getElementById("name");
var status = '';
function checkIt() {
if (alias.value != '') {
document.getElementById("alias").style.borderColor = "#3c763d";
return true;
} else {
document.getElementById("alias").style.borderColor = "#a94442";
status = false;
}
if (name.value != '') {
document.getElementById("name").style.borderColor = "#3c763d";
return true;
} else {
document.getElementById("name").style.borderColor = "#a94442";
status = false;
}
}
name.onblur=checkIt;
alias.onblur=checkIt;
Try this, you should use current object this instead of global variable when eventing firing
var alias = document.getElementById("alias");
var name = document.getElementById("name");
var status = '';
function checkIt() {
if (this.value != '') {
this.style.borderColor = "#3c763d";
status = true;
} else {
this.style.borderColor = "#a94442";
status = false;
}
}
name.onblur=checkIt;
alias.onblur=checkIt;
JSFIDDLE DEMO
Try this one:
Plain Js
script
var validate = function(e) {
var v = this.value;
this.style.borderColor = ('' !== v) ? '#3c763d' : '#a94442';
};
document.getElementById('alias').onblur = validate;
document.getElementById('name').onblur = validate;
JQuery
script
$(function(){
$("#alias, #name").on('focusout', function() {
var box = $(this);
var c = ('' !== box.val()) ? '#3c763d' : '#a94442';
box.css('border-color', c);
});
})

Error extract keyword from Google search in Javascript?

I have a sample code:
function getKeyword() {
var instance = this;
var googlePattern = /(www\.google\..*)/;
this.params = function(parameters) {
var result = [];
var params = parameters.split("&");
for(var p in params) {
var kv = params[p].split("=");
result[kv[0]] = kv[1];
}
return result;
};
this.googleKeywords = function(params){
var query = params["q"];
var pattern = /"(.*?)"|(\w+)/g;
return decodeURIComponent(query).replace(/\+/g, " ").match(pattern);
};
this.parseReferrer = function(){
var result = [];
var pathAndParams = document.referrer.split("?");
if(pathAndParams.length == 2) {
var path = pathAndParams[0];
var params = this.params(pathAndParams[1]);
if(path.search(googlePattern) > 0) {
result = this.googleKeywords(params);
}
}
return result;
};
return this.parseReferrer();
}
And then:
<script type="text/javascript">
if (document.referrer && document.referrer != "") {
if (document.referrer.search(/google\.*/i) != -1){
var keyword = getKeyword();
alert(keyword);
} else {
alert('Not search from google');
}
} else {
alert('Not referrer');
}
</script>
Ex: when i search with keyword is "iphone 5", result not show alert("iphone 5") ? How to fix it ?
The JavaScript for in construct loops over more than just the entries in the array. If you want to use for in you need to make sure that you're only processing the actual parameters. This is easiest accomplished by checking for hasOwnProperty:
this.params = function(parameters) {
var result = [];
var params = parameters.split("&");
for(var p in params) {
if (params.hasOwnProperty(p))
{
var kv = params[p].split("=");
result[kv[0]] = kv[1];
}
}
return result;
};
Alternatively you can use a regular for loop over the array:
this.params = function(parameters) {
var result = [];
var params = parameters.split("&");
for(var i=0; i < params.length; i++) {
var kv = params[i].split("=");
result[kv[0]] = kv[1];
}
return result;
};

Categories