Change select list to ul list. - javascript

I have a filterscript that is displayed as select dropdown. I would transform this to regular clickable text in a ul list. Is it possible to replace the select selector in the script somehow and keep the script intact?
<select id="ram" name="ram" class="select single" onchange="location.href=this.options[this.selectedIndex].value">
<option value="" selected="selected">Select / Reset</option>
<option value="2GB">2 GB</option>
<option value="4GB">4 GB</option>
<option value="8GB">8 GB</option>
</select>
Script:
$(document).ready(function(){
new function(settings) {
var $separator = settings.separator || '&';
var $spaces = settings.spaces === false ? false : true;
var $suffix = settings.suffix === false ? '' : '[]';
var $prefix = settings.prefix === false ? false : true;
var $hash = $prefix ? settings.hash === true ? "#" : "?" : "";
var $numbers = settings.numbers === false ? false : true;
jQuery.query = new function() {
var is = function(o, t) {
return o != undefined && o !== null && (!!t ? o.constructor == t : true);
};
var parse = function(path) {
var m, rx = /\[([^[]*)\]/g, match = /^([^[]+)(\[.*\])?$/.exec(path),base = match[1], tokens = [];
while (m = rx.exec(match[2])) tokens.push(m[1]);
return [base, tokens];
};
var set = function(target, tokens, value) {
var o, token = tokens.shift();
if (typeof target != 'object') target = null;
if (token === "") {
if (!target) target = [];
if (is(target, Array)) {
target.push(tokens.length == 0 ? value : set(null, tokens.slice(0), value));
} else if (is(target, Object)) {
var i = 0;
while (target[i++] != null);
target[--i] = tokens.length == 0 ? value : set(target[i], tokens.slice(0), value);
} else {
target = [];
target.push(tokens.length == 0 ? value : set(null, tokens.slice(0), value));
}
} else if (token && token.match(/^\s*[0-9]+\s*$/)) {
var index = parseInt(token, 10);
if (!target) target = [];
target[index] = tokens.length == 0 ? value : set(target[index], tokens.slice(0), value);
} else if (token) {
var index = token.replace(/^\s*|\s*$/g, "");
if (!target) target = {};
if (is(target, Array)) {
var temp = {};
for (var i = 0; i < target.length; ++i) {
temp[i] = target[i];
}
target = temp;
}
target[index] = tokens.length == 0 ? value : set(target[index], tokens.slice(0), value);
} else {
return value;
}
return target;
};
var queryObject = function(a) {
var self = this;
self.keys = {};
if (a.queryObject) {
jQuery.each(a.get(), function(key, val) {
self.SET(key, val);
});
} else {
self.parseNew.apply(self, arguments);
}
return self;
};
queryObject.prototype = {
queryObject: true,
parseNew: function(){
var self = this;
self.keys = {};
jQuery.each(arguments, function() {
var q = "" + this;
q = q.replace(/^[?#]/,''); // remove any leading ? || #
q = q.replace(/[;&]$/,''); // remove any trailing & || ;
if ($spaces) q = q.replace(/[+]/g,' '); // replace +'s with spaces
jQuery.each(q.split(/[&;]/), function(){
var key = decodeURIComponent(this.split('=')[0] || "");
var val = decodeURIComponent(this.split('=')[1] || "");
if (!key) return;
if ($numbers) {
if (/^[+-]?[0-9]+\.[0-9]*$/.test(val)) // simple float regex
val = parseFloat(val);
else if (/^[+-]?[0-9]+$/.test(val)) // simple int regex
val = parseInt(val, 10);
}
val = (!val && val !== 0) ? true : val;
self.SET(key, val);
});
});
return self;
},
has: function(key, type) {
var value = this.get(key);
return is(value, type);
},
GET: function(key) {
if (!is(key)) return this.keys;
var parsed = parse(key), base = parsed[0], tokens = parsed[1];
var target = this.keys[base];
while (target != null && tokens.length != 0) {
target = target[tokens.shift()];
}
return typeof target == 'number' ? target : target || "";
},
get: function(key) {
var target = this.GET(key);
if (is(target, Object))
return jQuery.extend(true, {}, target);
else if (is(target, Array))
return target.slice(0);
return target;
},
SET: function(key, val) {
var value = !is(val) ? null : val;
var parsed = parse(key), base = parsed[0], tokens = parsed[1];
var target = this.keys[base];
this.keys[base] = set(target, tokens.slice(0), value);
return this;
},
set: function(key, val) {
return this.copy().SET(key, val);
},
REMOVE: function(key) {
return this.SET(key, null).COMPACT();
},
remove: function(key) {
return this.copy().REMOVE(key);
},
EMPTY: function() {
var self = this;
jQuery.each(self.keys, function(key, value) {
delete self.keys[key];
});
return self;
},
load: function(url) {
var hash = url.replace(/^.*?[#](.+?)(?:\?.+)?$/, "$1");
var search = url.replace(/^.*?[?](.+?)(?:#.+)?$/, "$1");
return new queryObject(url.length == search.length ? '' : search, url.length == hash.length ? '' : hash);
},
empty: function() {
return this.copy().EMPTY();
},
copy: function() {
return new queryObject(this);
},
COMPACT: function() {
function build(orig) {
var obj = typeof orig == "object" ? is(orig, Array) ? [] : {} : orig;
if (typeof orig == 'object') {
function add(o, key, value) {
if (is(o, Array))
o.push(value);
else
o[key] = value;
}
jQuery.each(orig, function(key, value) {
if (!is(value)) return true;
add(obj, key, build(value));
});
}
return obj;
}
this.keys = build(this.keys);
return this;
},
compact: function() {
return this.copy().COMPACT();
},
toString: function() {
var i = 0, queryString = [], chunks = [], self = this;
var encode = function(str) {
str = str + "";
if ($spaces) str = str.replace(/ /g, "+");
return encodeURIComponent(str);
};
var addFields = function(arr, key, value) {
if (!is(value) || value === false) return;
var o = [encode(key)];
if (value !== true) {
o.push("=");
o.push(encode(value));
}
arr.push(o.join(""));
};
var build = function(obj, base) {
var newKey = function(key) {
return !base || base == "" ? [key].join("") : [base, "[", key, "]"].join("");
};
jQuery.each(obj, function(key, value) {
if (typeof value == 'object')
build(value, newKey(key));
else
addFields(chunks, newKey(key), value);
});
};
build(this.keys);
if (chunks.length > 0) queryString.push($hash);
queryString.push(chunks.join($separator));
return queryString.join("");
}
};
return new queryObject(location.search, location.hash);
};
}(jQuery.query || {}); // Pass in jQuery.query as settings object
function removeFSS() {
ga("send", "event", "button", "click", "filter-clear");
var t = encodeURI(unescape($.query.set("fss", '')));
var n = window.location.href.split("?")[0]; window.location.href = n + t
}
function getFSS() {
var D = jQuery('.filterGenius input, .filterGenius select').serializeArray();
var O = {};
jQuery.each(D, function(_, kv) {
if (O.hasOwnProperty(kv.name)) {
O[kv.name] = jQuery.makeArray(O[kv.name]);
O[kv.name].push(clean(kv.value, ""));
}
else {
O[kv.name] =kv.value;
}
});
var V = [];
for(var i in O)
if(jQuery.isArray(O[i]))
V.push(O[i].join("+"));
else
V.push(O[i]);
V = jQuery.grep(V,function(n){ return(n) });
return V.join("+");
}
$(document).ready(function () {
$(".filterGenius input").each(function () {
if (window.location.href.indexOf($(this).val()) >= 0) {
$(this).attr("checked", "checked")
}
});
$(".filterGenius select option").each(function () {
if (window.location.href.indexOf($(this).val()) >= 0) {
$(this).attr('selected', true);
}
});
$(".filterGenius input, .filterGenius select").change(function () {
var s = encodeURI(unescape(jQuery.query.set("fss", getFSS())));
var o = window.location.href.split("?")[0];
$(".filterGenius input, .filterGenius select").attr("disabled", true);
window.location.href = o + s
});
});
});

try to this way
$(function() {
$("<ul />").appendTo("nav");
$("nav select option").each(function() {
var el = $(this);
var li = $("<li />", {
"text" : el.text(),
}).appendTo("nav ul");
$(li).html('' + $(li).html() + '');
});
});
https://jsfiddle.net/99sgm51y/3/

Related

.JS not working on Chrome Extension

I'm working on my first Chrome extension to help me on my job.
Well, I have a HTML file as the extension pop-up and a .JS file to do all the magic. When I run the HTML in the browser, it works fine (it has to autocomplete the keywords are being typed) but when I run it as a Chrome extension it does not work at all.
Any idea?
JSON file
{
"name": "Autocompleter",
"version": "0",
"description": "It completes!",
"manifest_version": 2,
"browser_action": {
"name": "project with jquery",
"icons": ["icon.png"],
"default_icon": "icon.png",
"default_popup": "home.html"
},
"content_scripts": [ {
"js": [ "awesomplete.js" ],
"matches": [ "http://*/*", "https://*/*"]
}]
}
HTML
<!doctype html>
<html lang="en">
<head>
<script src="awesomplete.js"></script>
<link rel="stylesheet" href="awesomplete.css" />
</head>
<body>
<section id="multiple-values">
<input data-list="Brazil, Argentina, Uruguai, Paraguai, Nova Zelândia, Canadá" data-multiple data-minchars="1" /></label>
<pre class="language-javascript"><code><script>new Awesomplete('input[data-multiple]', {
filter: function(text, input) {
return Awesomplete.FILTER_CONTAINS(text, input.match(/[^,]*$/)[0]);
},
replace: function(text) {
var before = this.input.value.match(/^.+,\s*|/)[0];
this.input.value = before + text + ", ";
}
});</script></code></pre>
</section>
</body>
</html>
.JS file
(function () {
var _ = function (input, o) {
var me = this;
// Setup
this.isOpened = false;
this.input = $(input);
this.input.setAttribute("autocomplete", "off");
this.input.setAttribute("aria-autocomplete", "list");
o = o || {};
configure(this, {
minChars: 2,
maxItems: 10,
autoFirst: false,
data: _.DATA,
filter: _.FILTER_CONTAINS,
sort: _.SORT_BYLENGTH,
item: _.ITEM,
replace: _.REPLACE
}, o);
this.index = -1;
// Create necessary elements
this.container = $.create("div", {
className: "awesomplete",
around: input
});
this.ul = $.create("ul", {
hidden: "hidden",
inside: this.container
});
this.status = $.create("span", {
className: "visually-hidden",
role: "status",
"aria-live": "assertive",
"aria-relevant": "additions",
inside: this.container
});
// Bind events
$.bind(this.input, {
"input": this.evaluate.bind(this),
"blur": this.close.bind(this, { reason: "blur" }),
"keydown": function(evt) {
var c = evt.keyCode;
// If the dropdown `ul` is in view, then act on keydown for the following keys:
// Enter / Esc / Up / Down
if(me.opened) {
if (c === 13 && me.selected) { // Enter
evt.preventDefault();
me.select();
}
else if (c === 27) { // Esc
me.close({ reason: "esc" });
}
else if (c === 38 || c === 40) { // Down/Up arrow
evt.preventDefault();
me[c === 38? "previous" : "next"]();
}
}
}
});
$.bind(this.input.form, {"submit": this.close.bind(this, { reason: "submit" })});
$.bind(this.ul, {"mousedown": function(evt) {
var li = evt.target;
if (li !== this) {
while (li && !/li/i.test(li.nodeName)) {
li = li.parentNode;
}
if (li && evt.button === 0) { // Only select on left click
evt.preventDefault();
me.select(li, evt.target);
}
}
}});
if (this.input.hasAttribute("list")) {
this.list = "#" + this.input.getAttribute("list");
this.input.removeAttribute("list");
}
else {
this.list = this.input.getAttribute("data-list") || o.list || [];
}
_.all.push(this);
};
_.prototype = {
set list(list) {
if (Array.isArray(list)) {
this._list = list;
}
else if (typeof list === "string" && list.indexOf(",") > -1) {
this._list = list.split(/\s*,\s*/);
}
else { // Element or CSS selector
list = $(list);
if (list && list.children) {
var items = [];
slice.apply(list.children).forEach(function (el) {
if (!el.disabled) {
var text = el.textContent.trim();
var value = el.value || text;
var label = el.label || text;
if (value !== "") {
items.push({ label: label, value: value });
}
}
});
this._list = items;
}
}
if (document.activeElement === this.input) {
this.evaluate();
}
},
get selected() {
return this.index > -1;
},
get opened() {
return this.isOpened;
},
close: function (o) {
if (!this.opened) {
return;
}
this.ul.setAttribute("hidden", "");
this.isOpened = false;
this.index = -1;
$.fire(this.input, "awesomplete-close", o || {});
},
open: function () {
this.ul.removeAttribute("hidden");
this.isOpened = true;
if (this.autoFirst && this.index === -1) {
this.goto(0);
}
$.fire(this.input, "awesomplete-open");
},
next: function () {
var count = this.ul.children.length;
this.goto(this.index < count - 1 ? this.index + 1 : (count ? 0 : -1) );
},
previous: function () {
var count = this.ul.children.length;
var pos = this.index - 1;
this.goto(this.selected && pos !== -1 ? pos : count - 1);
},
// Should not be used, highlights specific item without any checks!
goto: function (i) {
var lis = this.ul.children;
if (this.selected) {
lis[this.index].setAttribute("aria-selected", "false");
}
this.index = i;
if (i > -1 && lis.length > 0) {
lis[i].setAttribute("aria-selected", "true");
this.status.textContent = lis[i].textContent;
$.fire(this.input, "awesomplete-highlight", {
text: this.suggestions[this.index]
});
}
},
select: function (selected, origin) {
if (selected) {
this.index = $.siblingIndex(selected);
} else {
selected = this.ul.children[this.index];
}
if (selected) {
var suggestion = this.suggestions[this.index];
var allowed = $.fire(this.input, "awesomplete-select", {
text: suggestion,
origin: origin || selected
});
if (allowed) {
this.replace(suggestion);
this.close({ reason: "select" });
$.fire(this.input, "awesomplete-selectcomplete", {
text: suggestion
});
}
}
},
evaluate: function() {
var me = this;
var value = this.input.value;
if (value.length >= this.minChars && this._list.length > 0) {
this.index = -1;
// Populate list with options that match
this.ul.innerHTML = "";
this.suggestions = this._list
.map(function(item) {
return new Suggestion(me.data(item, value));
})
.filter(function(item) {
return me.filter(item, value);
})
.sort(this.sort)
.slice(0, this.maxItems);
this.suggestions.forEach(function(text) {
me.ul.appendChild(me.item(text, value));
});
if (this.ul.children.length === 0) {
this.close({ reason: "nomatches" });
} else {
this.open();
}
}
else {
this.close({ reason: "nomatches" });
}
}
};
// Static methods/properties
_.all = [];
_.FILTER_CONTAINS = function (text, input) {
return RegExp($.regExpEscape(input.trim()), "i").test(text);
};
_.FILTER_STARTSWITH = function (text, input) {
return RegExp("^" + $.regExpEscape(input.trim()), "i").test(text);
};
_.SORT_BYLENGTH = function (a, b) {
if (a.length !== b.length) {
return a.length - b.length;
}
return a < b? -1 : 1;
};
_.ITEM = function (text, input) {
var html = input === '' ? text : text.replace(RegExp($.regExpEscape(input.trim()), "gi"), "<mark>$&</mark>");
return $.create("li", {
innerHTML: html,
"aria-selected": "false"
});
};
_.REPLACE = function (text) {
this.input.value = text.value;
};
_.DATA = function (item/*, input*/) { return item; };
// Private functions
function Suggestion(data) {
var o = Array.isArray(data)
? { label: data[0], value: data[1] }
: typeof data === "object" && "label" in data && "value" in data ? data : { label: data, value: data };
this.label = o.label || o.value;
this.value = o.value;
}
Object.defineProperty(Suggestion.prototype = Object.create(String.prototype), "length", {
get: function() { return this.label.length; }
});
Suggestion.prototype.toString = Suggestion.prototype.valueOf = function () {
return "" + this.label;
};
function configure(instance, properties, o) {
for (var i in properties) {
var initial = properties[i],
attrValue = instance.input.getAttribute("data-" + i.toLowerCase());
if (typeof initial === "number") {
instance[i] = parseInt(attrValue);
}
else if (initial === false) { // Boolean options must be false by default anyway
instance[i] = attrValue !== null;
}
else if (initial instanceof Function) {
instance[i] = null;
}
else {
instance[i] = attrValue;
}
if (!instance[i] && instance[i] !== 0) {
instance[i] = (i in o)? o[i] : initial;
}
}
}
// Helpers
var slice = Array.prototype.slice;
function $(expr, con) {
return typeof expr === "string"? (con || document).querySelector(expr) : expr || null;
}
function $$(expr, con) {
return slice.call((con || document).querySelectorAll(expr));
}
$.create = function(tag, o) {
var element = document.createElement(tag);
for (var i in o) {
var val = o[i];
if (i === "inside") {
$(val).appendChild(element);
}
else if (i === "around") {
var ref = $(val);
ref.parentNode.insertBefore(element, ref);
element.appendChild(ref);
}
else if (i in element) {
element[i] = val;
}
else {
element.setAttribute(i, val);
}
}
return element;
};
$.bind = function(element, o) {
if (element) {
for (var event in o) {
var callback = o[event];
event.split(/\s+/).forEach(function (event) {
element.addEventListener(event, callback);
});
}
}
};
$.fire = function(target, type, properties) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent(type, true, true );
for (var j in properties) {
evt[j] = properties[j];
}
return target.dispatchEvent(evt);
};
$.regExpEscape = function (s) {
return s.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&");
};
$.siblingIndex = function (el) {
/* eslint-disable no-cond-assign */
for (var i = 0; el = el.previousElementSibling; i++);
return i;
};
// Initialization
function init() {
$$("input.awesomplete").forEach(function (input) {
new _(input);
});
}
// Are we in a browser? Check for Document constructor
if (typeof Document !== "undefined") {
// DOM already loaded?
if (document.readyState !== "loading") {
init();
}
else {
// Wait for it
document.addEventListener("DOMContentLoaded", init);
}
}
_.$ = $;
_.$$ = $$;
// Make sure to export Awesomplete on self when in a browser
if (typeof self !== "undefined") {
self.Awesomplete = _;
}
// Expose Awesomplete as a CJS module
if (typeof module === "object" && module.exports) {
module.exports = _;
}
return _;
}());
Prints:
Working
Not working (as a Chrome Extension)

Serializing form with nested paths and arrays to JSON in javascript

A similar question is addressed here: Convert form data to JavaScript object with jQuery with the following solution:
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
However that doesn't work when you want to have JSON with nested objects. For instance, for this form:
Employee name: <input type="text" id="employee" name="name"/>
Department name: <input type="text" id="department" name="department.name"/>
Department chief1: <input type="text" id="chief1" name="department.chief[0]"/>
Department chief2: <input type="text" id="chief2" name="department.chief[1]"/>
I am getting: {"name":"John","department.name":"IT" , "department.chief[0]":"Mike" "department.chief[1]":"Lucas"}
but what I do need is {"name":"John","department" : {"name":"IT"}, "chief" : [ "Mike", "Lucas" }
Is there any adaptation of serializeObject that does it this way?
To provide some background: I need this because I am submitting an AJAX call to a Spring MVC controller and Jackson expects that format to create the nested objects.
This is my modified version of serializeObject supporting both nested objects and arrays:
$.fn.serializeObject = function() {
var arrayData, objectData;
arrayData = this.serializeArray();
objectData = {};
$.each(arrayData, function() {
this.value = !this.value ? '' : this.value;
processObject(objectData, this.name, this.value);
});
return objectData;
};
function processObject(obj, key, value){
if(key.indexOf('.') != -1) {
var attrs = key.split('.');
var tx = obj;
for (var i = 0; i < attrs.length - 1; i++) {
var isArray = attrs[i].indexOf('[') != -1;
var isNestedArray = isArray && (i != attrs.length-1);
var nestedArrayIndex = null;
if(isArray){
nestedArrayIndex = attrs[i].substring(attrs[i].indexOf('[') +1 , attrs[i].indexOf(']'));
attrs[i] = attrs[i].substring(0, attrs[i].indexOf('['));
if (tx[attrs[i]] == undefined){
tx[attrs[i]] = [];
}
tx = tx[attrs[i]];
if(isNestedArray){
if(tx[nestedArrayIndex] == undefined){
tx[nestedArrayIndex] = {};
}
tx = tx[nestedArrayIndex];
}
}else{
if (tx[attrs[i]] == undefined){
tx[attrs[i]] = {};
}
tx = tx[attrs[i]];
}
}
processObject(tx, attrs[attrs.length - 1], value);
}else{
var finalArrayIndex = null;
if(key.indexOf('[') != -1){
finalArrayIndex = key.substring(key.indexOf('[') +1 , key.indexOf(']'));
key = key.substring(0, key.indexOf('['));
}
if(finalArrayIndex == null){
obj[key] = value;
}else{
if(obj[key] == undefined){
obj[key] = [];
}
obj[key][finalArrayIndex] = value;
}
}
}
unflatten from the (npm) "flat" module should do the trick:
var data = {"name":"John","department.name":"IT"}
var nested = flat.unflatten(data)
Live example
https://tonicdev.com/lipp/unflatten
Just replace return o with return flat.unlatten(o) in your case.
This is the unflatten method for the browser extracted and un-noded from repo(https://github.com/hughsk/flat/blob/master/index.js):
function unflatten(target, opts) {
opts = opts || {}
var delimiter = opts.delimiter || '.'
var overwrite = opts.overwrite || false
var result = {}
// safely ensure that the key is
// an integer.
function getkey(key) {
var parsedKey = Number(key)
return (
isNaN(parsedKey) ||
key.indexOf('.') !== -1
) ? key
: parsedKey
}
Object.keys(target).forEach(function(key) {
var split = key.split(delimiter)
var key1 = getkey(split.shift())
var key2 = getkey(split[0])
var recipient = result
while (key2 !== undefined) {
var type = Object.prototype.toString.call(recipient[key1])
var isobject = (
type === "[object Object]" ||
type === "[object Array]"
)
// do not write over falsey, non-undefined values if overwrite is false
if (!overwrite && !isobject && typeof recipient[key1] !== 'undefined') {
return
}
if ((overwrite && !isobject) || (!overwrite && recipient[key1] == null)) {
recipient[key1] = (
typeof key2 === 'number' &&
!opts.object ? [] : {}
)
}
recipient = recipient[key1]
if (split.length > 0) {
key1 = getkey(split.shift())
key2 = getkey(split[0])
}
}
// unflatten again for 'messy objects'
recipient[key1] = unflatten(target[key], opts)
})
return result
}

Instagram instafeed Image rotator/Slider

This is my first post on StackOverflow and might I say, what a great and helpful resource this is. I have been able to find many answers to my questions and hope to do the same with this one. On to the issue at hand... I am currently using the instafeed.js (http://instafeedjs.com/) script to pull in images from instagram and display them on my site.
What I'm trying to accomplish is to have 9 items display, then if I hit the "next" button, it would replace the current 9 images and load the next 9 images and, if the "previous" button is clicked it would go back and show the previous 9 images.
Currently it only renders one image thumb that scrolls through 9 images then stops. Swapping only the one image at a time. A sample of the current working code with only 1 image displaying can be found here - http://codepen.io/stevenschobert/pen/iHxfw
Here is my JavaScript for the instafeed call:
var count = 1;
var feed;
feed = new Instafeed({
clientId: '68be8b63013048ff81bb4ac8b02b606e',
limit: 9,
resolution: 'standard_resolution',
template: '<img src="{{image}}" /><div class="likes">♥ {{likes}}</div>',
mock: true,
after: function () {
var images = $("#instafeed").find('a');
$.each(images, function(index, image) {
var delay = (index * 75) + 'ms';
$(image).css('-webkit-animation-delay', delay);
$(image).css('-moz-animation-delay', delay);
$(image).css('-ms-animation-delay', delay);
$(image).css('-o-animation-delay', delay);
$(image).css('animation-delay', delay);
$(image).addClass('animated fadeInUp pic-'+count++);
});
},
custom: {
images: [],
currentImage: 0,
showImage: function () {
var result, image;
image = this.options.custom.images[this.options.custom.currentImage];
result = this._makeTemplate(this.options.template, {
model: image,
id: image.id,
link: image.link,
image: image.images[this.options.resolution].url,
caption: this._getObjectProperty(image, 'caption.text'),
likes: image.likes.count,
comments: image.comments.count,
location: this._getObjectProperty(image, 'location.name')
});
$("#instafeed").html(result);
}
},
success: function (data) {
this.options.custom.images = data.data;
this.options.custom.showImage.call(this);
}
});
feed.run();
$(".next").click(function () {
var length, current;
current = feed.options.custom.currentImage;
length = feed.options.custom.images.length;
if (current < length - 1) {
feed.options.custom.currentImage++;
feed.options.custom.showImage.call(feed);
}
});
$(".prev").click(function () {
var length, current;
current = feed.options.custom.currentImage;
length = feed.options.custom.images.length;
if (current > 0) {
feed.options.custom.currentImage--
feed.options.custom.showImage.call(feed);
}
});
My HTML:
<div id="instafeed"></div>
<div class="controls">
<div class="prev"><- prev</div>
<div class="next">next -></div>
</div>
The Instafeed.js code:
(function() { var Instafeed, root; Instafeed = (function() {
function Instafeed(params) {
var option, value;
this.options = {
target: 'instafeed',
get: 'popular',
resolution: 'thumbnail',
sortBy: 'most-recent',
links: true,
limit: 15,
mock: false
};
if (typeof params === 'object') {
for (option in params) {
value = params[option];
this.options[option] = value;
}
}
this.unique = this._genKey();
}
Instafeed.prototype.run = function() {
var header, instanceName, script;
if (typeof this.options.clientId !== 'string') {
if (typeof this.options.accessToken !== 'string') {
throw new Error("Missing clientId or accessToken.");
}
}
if (typeof this.options.accessToken !== 'string') {
if (typeof this.options.clientId !== 'string') {
throw new Error("Missing clientId or accessToken.");
}
}
if ((this.options.before != null) && typeof this.options.before === 'function') {
this.options.before.call(this);
}
if (typeof document !== "undefined" && document !== null) {
script = document.createElement('script');
script.id = 'instafeed-fetcher';
script.src = this._buildUrl();
header = document.getElementsByTagName('head');
header[0].appendChild(script);
instanceName = "instafeedCache" + this.unique;
window[instanceName] = new Instafeed(this.options);
window[instanceName].unique = this.unique;
}
return true;
};
Instafeed.prototype.parse = function(response) {
var anchor, fragment, header, htmlString, image, imageString, images, img, instanceName, reverse, sortSettings, _i, _j, _len, _len1;
if (typeof response !== 'object') {
if ((this.options.error != null) && typeof this.options.error === 'function') {
this.options.error.call(this, 'Invalid JSON data');
return false;
} else {
throw new Error('Invalid JSON response');
}
}
if (response.meta.code !== 200) {
if ((this.options.error != null) && typeof this.options.error === 'function') {
this.options.error.call(this, response.meta.error_message);
return false;
} else {
throw new Error("Error from Instagram: " + response.meta.error_message);
}
}
if (response.data.length === 0) {
if ((this.options.error != null) && typeof this.options.error === 'function') {
this.options.error.call(this, 'No images were returned from Instagram');
return false;
} else {
throw new Error('No images were returned from Instagram');
}
}
if ((this.options.success != null) && typeof this.options.success === 'function') {
this.options.success.call(this, response);
}
if (this.options.sortBy !== 'most-recent') {
if (this.options.sortBy === 'random') {
sortSettings = ['', 'random'];
} else {
sortSettings = this.options.sortBy.split('-');
}
reverse = sortSettings[0] === 'least' ? true : false;
switch (sortSettings[1]) {
case 'random':
response.data.sort(function() {
return 0.5 - Math.random();
});
break;
case 'recent':
response.data = this._sortBy(response.data, 'created_time', reverse);
break;
case 'liked':
response.data = this._sortBy(response.data, 'likes.count', reverse);
break;
case 'commented':
response.data = this._sortBy(response.data, 'comments.count', reverse);
break;
default:
throw new Error("Invalid option for sortBy: '" + this.options.sortBy + "'.");
}
}
if ((typeof document !== "undefined" && document !== null) && this.options.mock === false) {
document.getElementById(this.options.target).innerHTML = '';
images = response.data;
if (images.length > this.options.limit) {
images = images.slice(0, this.options.limit + 1 || 9e9);
}
if ((this.options.template != null) && typeof this.options.template === 'string') {
htmlString = '';
imageString = '';
for (_i = 0, _len = images.length; _i < _len; _i++) {
image = images[_i];
imageString = this._makeTemplate(this.options.template, {
model: image,
id: image.id,
link: image.link,
image: image.images[this.options.resolution].url,
caption: this._getObjectProperty(image, 'caption.text'),
likes: image.likes.count,
comments: image.comments.count,
location: this._getObjectProperty(image, 'location.name')
});
htmlString += imageString;
}
document.getElementById(this.options.target).innerHTML = htmlString;
} else {
fragment = document.createDocumentFragment();
for (_j = 0, _len1 = images.length; _j < _len1; _j++) {
image = images[_j];
img = document.createElement('img');
img.src = image.images[this.options.resolution].url;
if (this.options.links === true) {
anchor = document.createElement('a');
anchor.href = image.images['standard_resolution'].url;
anchor.rel = "lightbox";
anchor.appendChild(img);
fragment.appendChild(anchor);
} else {
fragment.appendChild(img);
}
}
document.getElementById(this.options.target).appendChild(fragment);
}
header = document.getElementsByTagName('head')[0];
header.removeChild(document.getElementById('instafeed-fetcher'));
instanceName = "instafeedCache" + this.unique;
delete window[instanceName];
}
if ((this.options.after != null) && typeof this.options.after === 'function') {
this.options.after.call(this);
}
return true;
};
Instafeed.prototype._buildUrl = function() {
var base, endpoint, final;
base = "https://api.instagram.com/v1";
switch (this.options.get) {
case "popular":
endpoint = "media/popular";
break;
case "tagged":
if (typeof this.options.tagName !== 'string') {
throw new Error("No tag name specified. Use the 'tagName' option.");
}
endpoint = "tags/" + this.options.tagName + "/media/recent";
break;
case "location":
if (typeof this.options.locationId !== 'number') {
throw new Error("No location specified. Use the 'locationId' option.");
}
endpoint = "locations/" + this.options.locationId + "/media/recent";
break;
case "user":
if (typeof this.options.userId !== 'number') {
throw new Error("No user specified. Use the 'userId' option.");
}
if (typeof this.options.accessToken !== 'string') {
throw new Error("No access token. Use the 'accessToken' option.");
}
endpoint = "users/" + this.options.userId + "/media/recent";
break;
default:
throw new Error("Invalid option for get: '" + this.options.get + "'.");
}
final = "" + base + "/" + endpoint;
if (this.options.accessToken != null) {
final += "?access_token=" + this.options.accessToken;
} else {
final += "?client_id=" + this.options.clientId;
}
final += "&count=" + this.options.limit;
final += "&callback=instafeedCache" + this.unique + ".parse";
return final;
};
Instafeed.prototype._genKey = function() {
var S4;
S4 = function() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
};
return "" + (S4()) + (S4()) + (S4()) + (S4());
};
Instafeed.prototype._makeTemplate = function(template, data) {
var output, pattern, varName, varValue, _ref;
pattern = /(?:\{{2})([\w\[\]\.]+)(?:\}{2})/;
output = template;
while (pattern.test(output)) {
varName = output.match(pattern)[1];
varValue = (_ref = this._getObjectProperty(data, varName)) != null ? _ref : '';
output = output.replace(pattern, "" + varValue);
}
return output;
};
Instafeed.prototype._getObjectProperty = function(object, property) {
var piece, pieces;
property = property.replace(/\[(\w+)\]/g, '.$1');
pieces = property.split('.');
while (pieces.length) {
piece = pieces.shift();
if ((object != null) && piece in object) {
object = object[piece];
} else {
return null;
}
}
return object;
};
Instafeed.prototype._sortBy = function(data, property, reverse) {
var sorter;
sorter = function(a, b) {
var valueA, valueB;
valueA = this._getObjectProperty(a, property);
valueB = this._getObjectProperty(b, property);
if (reverse) {
if (valueA > valueB) {
return 1;
} else {
return -1;
}
}
if (valueA < valueB) {
return 1;
} else {
return -1;
}
};
data.sort(sorter.bind(this));
return data;
};
return Instafeed;})(); root = typeof exports !== "undefined" && exports !== null ? exports : window; root.Instafeed = Instafeed;}).call(this);
Any help with this issue would be GREATLY appreciated.
Thank You,
Jason

jQuery - Storing tags using cookies or local Storage using jquerytagbox plugin

I'm trying to save the tags from jQuery TagBox Plugin (from geektantra.com/2011/05/jquery-tagbox-plugin/)
(function(jQuery) {
jQuery.fn.tagBox = function(options) {
var defaults = {
separator: ',',
className: 'tagBox',
tagInputClassName: '',
tagButtonClassName: '',
tagButtonTitle: 'Add Tag',
confirmRemoval: false,
confirmRemovalText: 'Do you really want to remove the tag?',
completeOnSeparator: true,
completeOnBlur: false,
readonly: false,
enableDropdown: false,
dropdownSource: function() {},
dropdownOptionsAttribute: "title",
removeTagText: "X",
maxTags: -1,
maxTagsErr: function(max_tags) { alert("A maximum of "+max_tags+" tags can be added!"); },
beforeTagAdd: function(tag_to_add) {},
afterTagAdd: function(added_tag) {}
}
if (options) {
options = jQuery.extend(defaults, options);
} else {
options = defaults;
}
options.tagInputClassName = ( options.tagInputClassName != '' ) ? options.tagInputClassName + ' ' : '';
options.tagButtonClassName = ( options.tagButtonClassName != '' ) ? options.tagButtonClassName + ' ' : '';
// Hide Element
var $elements = this;
if($elements.length < 1) return;
$elements.each(function(){
var uuid = Math.round( Math.random()*0x10000 ).toString(16) + Math.round( Math.random()*0x10000 ).toString(16);
var $element = jQuery(this);
$element.hide();
try {
var options_from_attribute = jQuery.parseJSON($element.attr(options.dropdownOptionsAttribute));
options = jQuery.extend(options_from_attribute, options);
} catch(e) {
console.log(e);
}
if($element.is(":disabled"))
options.readonly = true;
if( (jQuery.isArray($element)) && $element[0].hasAttribute("readonly") )
options.readonly = true
// Create DOM Elements
if( (options.enableDropdown) && options.dropdownSource() != null ) {
if(options.dropdownSource().jquery) {
var $tag_input_elem = (options.readonly) ? '' : options.dropdownSource();
$tag_input_elem.attr("id", options.className+'-input-'+uuid);
$tag_input_elem.addClass(options.className+'-input');
} else {
var tag_dropdown_items_obj = jQuery.parseJSON(options.dropdownSource());
var tag_dropdown_options = new Array('<option value=""></option>');
jQuery.each(tag_dropdown_items_obj, function(i, v){
if((jQuery.isArray(v)) && v.length == 2 ) {
tag_dropdown_options.push( '<option value="'+v[0]+'">'+v[1]+'</option>' );
} else if ( !jQuery.isArray(v) ) {
tag_dropdown_options.push( '<option value="'+i+'">'+v+'</option>' );
}
});
var tag_dropdown = '<select class="'+options.tagInputClassName+' '+options.className+'-input" id="'+options.className+'-input-'+uuid+'">'+tag_dropdown_options.join("")+'</select>';
var $tag_input_elem = (options.readonly) ? '' : jQuery(tag_dropdown);
}
} else {
var $tag_input_elem = (options.readonly) ? '' : jQuery('<input type="text" class="'+options.tagInputClassName+' '+options.className+'-input" value="" id="'+options.className+'-input-'+uuid+'" />');
}
var $tag_add_elem = (options.readonly) ? '' : jQuery(''+options.tagButtonTitle+'');
var $tag_list_elem = jQuery('<span class="'+options.className+'-list" id="'+options.className+'-list-'+uuid+'"></span>');
var $tagBox = jQuery('<span class="'+options.className+'-container"></span>').append($tag_input_elem).append($tag_add_elem).append($tag_list_elem);
$element.before($tagBox);
$element.addClass("jQTagBox");
$element.unbind('reloadTagBox');
$element.bind('reloadTagBox', function(){
$tagBox.remove();
$element.tagBox(options);
});
// Generate Tags List from Input item
generate_tags_list( get_current_tags_list() );
if(!options.readonly) {
$tag_add_elem.click(function() {
var selected_tag = $tag_input_elem.val();
options.beforeTagAdd(selected_tag);
add_tag(selected_tag);
if($tag_input_elem.is("select")) {
$tag_input_elem.find('option[value="'+selected_tag+'"]').attr("disabled", "disabled");
}
$tag_input_elem.val('');
options.afterTagAdd(selected_tag);
});
$tag_input_elem.keypress(function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
var this_val = jQuery(this).val();
if(code==13 || (code == options.separator.charCodeAt(0) && options.completeOnSeparator) ) {
$tag_add_elem.trigger("click");
return false;
}
});
if( options.completeOnBlur ) {
$tag_input_elem.blur(function() {
if(jQuery(this).val() != "")
$tag_add_elem.trigger("click");
});
}
jQuery('.'+options.className+'-remove-'+uuid).live( "click", function () {
if(options.confirmRemoval) {
var c = confirm(options.confirmRemovalText);
if(!c) return false;
}
var tag_item = jQuery(this).attr('rel');
if($tag_input_elem.is("select")) {
$tag_input_elem.find('option[value="'+tag_item+'"]').removeAttr("disabled");
}
$tag_input_elem.val('');
remove_tag(tag_item);
});
}
// Methods
function separator_encountered(val) {
return (val.indexOf( options.separator ) != "-1") ? true : false;
}
function get_current_tags_list() {
var tags_list = $element.val().split(options.separator);
tags_list = jQuery.map(tags_list, function (item) { return jQuery.trim(item); });
return tags_list;
}
function generate_tags_list(tags_list) {
var tags_list = jQuery.unique( tags_list.sort() ).sort();
$tag_list_elem.html('');
jQuery.each(tags_list, function(key, val) {
if(val != "") {
var remove_tag_link = (options.readonly) ? '' : ''+options.removeTagText+'';
if((options.enableDropdown) && jQuery('#'+options.className+'-input-'+uuid).find("option").length > 0) {
var display_val = jQuery('#'+options.className+'-input-'+uuid).find("option[value='"+val+"']").text();
} else {
var display_val = val;
}
$tag_list_elem.append('<span class="'+options.className+'-item"><span class="'+options.className+'-bullet">•</span><span class="'+options.className+'-item-content">'+remove_tag_link+''+display_val+'</span></span>');
}
});
$element.val(tags_list.join(options.separator));
}
function add_tag(new_tag_items) {
var tags_list = get_current_tags_list();
new_tag_items = new_tag_items.split(options.separator);
new_tag_items = jQuery.map(new_tag_items, function (item) { return jQuery.trim(item); });
tags_list = tags_list.concat(new_tag_items);
tags_list = jQuery.map( tags_list, function(item) { if(item != "") return item } );
if( tags_list.length > options.maxTags && options.maxTags != -1 ) {
options.maxTagsErr(options.maxTags);
return;
}
generate_tags_list(tags_list);
}
function remove_tag(old_tag_items) {
var tags_list = get_current_tags_list();
old_tag_items = old_tag_items.split(options.separator);
old_tag_items = jQuery.map(old_tag_items, function (item) { return jQuery.trim(item); });
jQuery.each( old_tag_items, function(key, val) {
tags_list = jQuery.grep(tags_list, function(value) { return value != val; })
});
generate_tags_list(tags_list);
}
});
}
})(jQuery);
What I want to do is save the new tags using cookies with jquerycooie.js or using localStorage, but after this:
<div class="row">
<label for="jquery-tagbox-text">Text TagBox (Comma Separated)</label>
<input id="jquery-tagbox-text" type="text" />
</div>
if I add
$.cookie('thetags', 'tags');
and than refresh the page nothing is saved. Any idea or help?
Probably the easiest way to do this would be to use the afterTagAdd callback and (adding) a afterTagRemove callback.
afterTagAdd: function() {
$.cookie('tags', this.get_current_tags_list().join(','));
added_tag();
}
afterTagRemove: function() {
$.cookie('tags', this.get_current_tags_list().join(','));
}
When you load the page, you need to add logic to add all of the cookie-cached values to the tags.
tagBox.add_tag($.cookie('tags'));
All of this is assuming that the separator you passed to TagBox is ','.

remove onclick function and change to onload or document.ready

What would be the easiest way to remove the onclick event from this script?
The script below uses google translate to translate from one language to another.
I want to be able to set the language to a
Request.Form("language")
so when I submit a form it will set the language. (I can do this so it is not a problem, however once this language is set I want the script to automatically translate the text.
something like
<body onload="">
or
document.ready or
translate.ready
However I am not 100% sure how to do this:
<script type='text/javascript'>
google.load("language", "1");
var translator = false;
function init(){
var str = $("source").innerHTML;
var triggerCollection = $("langSelect").select("li");
triggerCollection.invoke("observe", "click", handleTriggerClick);
translator = new Translator("source", "p,ul");
translator.addEventListener("complete", function(obj){
//console.log("The translation has finished %o", obj);
{
document.form1.g_content_text.value = $("source").innerHTML;
}{
//document.form1.submit();
}
});
translator.addEventListener("begin", function(obj){
//console.log("Translation has begun! %o", obj);
});
//console.log(translator.textNodeCollection);
}
function handleTriggerClick(e){
var lang = e.element().getAttribute("lang"); // This is the language to translate to!
var str = $("source").innerHTML;
translator.translate(lang);
}
function insertToForeign(obj){
$("display").innerHTML = obj.translation;
}
google.setOnLoadCallback(init);
var Translator = Class.create(EventDispatcher, {
initialize : function(element, selector, config){
this.element = $(element);
this.preservedHTML = this.element.innerHTML;
this.config = Object.extend(this.getDefaultConfig(), config);
this.textNodeCollection = this.collectChildren(selector);
this.preservedParentHash = {};
this.placeHolderHash = {};
this.entityWasher = new Element("div");
this.textNodeCollection = this.textNodeCollection.findAll(this.purifyTextNode);
},
purifyTextNode : function(node){
try{
if(!node)
return false;
return node.nodeType == 3;
}
catch(e){
return false;
}
},
getDefaultConfig : function(){
return { maxLength : 1000, srcLang : "en", recursive : true, type : "text" };
},
collectChildren : function(selector){
return this.element.select(selector).collect(this.collectTextNodes.bind(this)).flatten();
},
collectTextNodes : function(element){
var self = this;
var stack = $A(element.childNodes).collect(function(child){
if(child.nodeType == 3 && child.nodeValue.length < self.config.maxLength && child.nodeValue.search(/^\s+$/g) == -1)
return child;
else if(child.nodeType == 3 && child.nodeValue.length > self.config.maxLength)
return self.splitTextNode(child);
else if(child.nodeType == 1 && self.config.recursive)
return self.collectTextNodes(child);
});
return stack;
},
splitStringByMax : function(text){
var offset = 0;
var textArr = [];
while(text.length > this.config.maxLength){
var tmp = text.substr(0, this.config.maxLength);
offset = tmp.lastIndexOf(" ");
var subText = text.substr(0, offset);
text = text.substr(offset);
textArr.push(subText);
}
textArr.push(text);
return textArr;
},
splitTextNode : function(node){
var nodeStack = [];
var textArr = this.splitStringByMax(node.nodeValue);
var prevNode = false;
textArr.each(function(text, itr){
var newNode = document.createTextNode(text);
nodeStack.push(newNode);
if(node.nextSibling != null && !prevNode)
node.parentNode.insertBefore(newNode, node.nextSibling);
else if(prevNode && prevNode.nextSibling != null)
node.parentNode.insertBefore(newNode, prevNode.nextSibling);
else
node.parentNode.appendChild(newNode);
prevNode = newNode;
});
node.parentNode.removeChild(node);
return nodeStack;
},
getEventBeginObject : function(destLang){
return {
destLang : destLang,
srcLang : this.config.srcLang,
srcLangNodes : this.textNodeCollection,
srcHTML : this.preservedHTML
}
},
getEventCompleteObject : function(result){
return {
srcLangNodes : this.textNodeCollection,
destLangNodes : this.translationStack,
destLangHTML : this.element.innerHTML,
srcLangHTML : this.preservedHTML,
result : result,
resultStack : this.resultStack
}
},
finishTranslation : function(result){
this.translating = false;
this.dispatchEvent("complete", this.getEventCompleteObject(result));
},
translate : function(destLang){
if(this.translating)
return false;
var self = this;
this.dispatchEvent("begin", this.getEventBeginObject(destLang));
this.textNodeCount = this.textNodeCollection.length;
this.translationStack = [];
this.resultStack = [];
this.textNodeCollection.each(function(node, index){
self.translating = true;
google.language.translate(node.nodeValue, self.config.srcLang, destLang, self.handleTranslation.bind(self, node, index));
});
return true;
},
getPreservedParent : function(node, index){
if(this.preservedParentHash[index])
return this.preservedParentHash[index];
return this.preservedParentHash[index] = node.parentNode;
},
getPlaceHolder : function(index){
return this.placeHolderHash[index] || false;
},
setPlaceHolder : function(node, index){
this.placeHolderHash[index] = node;
},
handleTranslation : function(node, index, obj){
try{
var parent = this.getPreservedParent(node, index);
this.entityWasher.innerHTML = obj.translation;
var translatedText = this.entityWasher.innerHTML;
if(node.nodeValue.search(/^\s/) > -1)
translatedText = " " + translatedText;
if(node.nodeValue.search(/\s$/) > -1)
translatedText = translatedText + " ";
var newText = document.createTextNode(translatedText);
if(this.getPlaceHolder(index))
parent.replaceChild(newText, this.getPlaceHolder(index));
else
parent.replaceChild(newText, node);
this.setPlaceHolder(newText, index);
this.translationStack.push(newText);
this.resultStack.push(obj);
this.textNodeCount--;
if(this.textNodeCount <= 0)
this.finishTranslation(obj);
}
catch(e){
console.log("Error has occured with handling translation error = %o arguments = %o", e, arguments);
}
}
});
</script>
if you click on the li it sets the language and start the function:
<ul id="langSelect">
<li lang="de">German</li></ul>
another solution might be to similate a user click on the li command, but I am also not sure how to do this!
Any help would be appreciated.
Any help would be appreciated
I think part of the problem lies here:
triggerCollection.invoke("observe", "click", handleTriggerClick);
It sounds like you are interested in the dom:loaded event.
document.observe("dom:loaded", function() {
translator.translate($('langselect').getAttribute('lang'));
});
Or if you know the language code you can feed it in directly. For the german example:
translator.translate('de');

Categories

Resources