remove onclick function and change to onload or document.ready - javascript

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

Related

JavaScript array has elements but length is zero

I've done some searching around the web and nothing seems to solve my problem. I have the following jQuery code:
function youtube_data_parser(data) {
//---> parse video data - start
var qsToJson = function(qs) {
var res = {};
var pars = qs.split('&');
var kv, k, v;
for (i in pars) {
kv = pars[i].split('=');
k = kv[0];
v = kv[1];
res[k] = decodeURIComponent(v);
}
return res;
}
//---> parse video data - end
var get_video_info = qsToJson(data);
if (get_video_info.status == 'fail') {
return {
status: "error",
code: "invalid_url",
msg: "check your url or video id"
};
} else {
// remapping urls into an array of objects
//--->parse > url_encoded_fmt_stream_map > start
//will get the video urls
var tmp = get_video_info["url_encoded_fmt_stream_map"];
if (tmp) {
tmp = tmp.split(',');
for (i in tmp) {
tmp[i] = qsToJson(tmp[i]);
}
get_video_info["url_encoded_fmt_stream_map"] = tmp;
}
//--->parse > url_encoded_fmt_stream_map > end
//--->parse > player_response > start
var tmp1 = get_video_info["player_response"];
if (tmp1) {
get_video_info["player_response"] = JSON.parse(tmp1);
}
//--->parse > player_response > end
//--->parse > keywords > start
var keywords = get_video_info["keywords"];
if (keywords) {
key_words = keywords.replace(/\+/g, ' ').split(',');
for (i in key_words) {
keywords[i] = qsToJson(key_words[i]);
}
get_video_info["keywords"] = {
all: keywords.replace(/\+/g, ' '),
arr: key_words
};
}
//--->parse > keywords > end
//return data
return {
status: 'success',
raw_data: qsToJson(data),
video_info: get_video_info
};
}
}
function getVideoInfo() {
var get_video_url = $('#ytdlUrl').val();
var get_video_id = getUrlVars(get_video_url)['v'];
var video_arr_final = [];
var ajax_url = "video_info.php?id=" + get_video_id;
$.get(ajax_url, function(d1) {
var data = youtube_data_parser(d1);
var video_data = data.video_info;
var player_info = data.video_info.player_response;
var video_title = player_info.videoDetails.title.replace(/\+/g, ' ');
var fmt_list = video_data.fmt_list.split(',');
var video_thumbnail_url = video_data.thumbnail_url;
var video_arr = video_data.url_encoded_fmt_stream_map;
//create video file array
$.each(video_arr, function(i1, v1) {
var valueToPush = {};
valueToPush.video_url = v1.url;
valueToPush.video_thumbnail_url = video_thumbnail_url;
valueToPush.video_title = video_title;
$.each(fmt_list, function(i2, v2) {
var fmt = v2.split('/');
var fmt_id = fmt[0];
var fmt_quality = fmt[1];
if (fmt_id == v1.itag) {
valueToPush.fmt_id = fmt_id;
valueToPush.fmt_quality = fmt_quality;
}
});
video_arr_final.push(valueToPush);
});
});
return video_arr_final;
}
function getUrlVars(url) {
var vars = {};
var parts = url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m, key, value) {
vars[key] = value;
});
return vars;
}
function fillInOptions(ytOptions) {
//console.log(ytOptions);
//alert(ytOptions[0]);
var ytFill = ytOptions;
console.log(ytFill);
//ytFill.forEach(function(i,v) {
var ytdlOptions = $('#ytdlOptions');
ytFill.forEach(function(i,v) {
console.log(i);
ytdlOptions.append(new Option(v.fmt_quality, v.fmt_id));
});
return true;
}
function showYTDLLoader() {
$('#ytdlInput').fadeOut(1000, function() {
$('#ytdlLoader').fadeIn(500);
});
var options = getVideoInfo();
//console.log(options);
if (fillInOptions(options) == true) {
//do rest
}
}
function showYTDLOptions() {
return true;
}
function startDownload() {
showYTDLLoader();
}
function hideYTDLLoader() {
$('#ytdlLoader').fadeOut(500);
}
function animateCSS(element, animationName, callback) {
const node = $(element);
node.addClass(animationName);
function handleAnimationEnd() {
node.removeClass(animationName);
node.animationend = null;
if (typeof callback === 'function') callback();
}
node.animationend = handleAnimationEnd();
}
When my button is clicked, I call showYTDLLoader() which gets an array of objects from the YouTube API that looks like this:
[
{
"video_url": "https://r7---sn-uxanug5-cox6.googlevideo.com/videoplayback?expire=1572496003&ei=Iw66Xa24H8PL3LUPiN25mAs&ip=2001%3A8003%3A749b%3Aa01%3A5cd8%3Ac610%3A6402%3Ad0fe&id=o-ADsVnoOoBQ6-SWzYZU7gHES06s7xQptJG6hn9WcakITY&itag=22&source=youtube&requiressl=yes&mm=31%2C29&mn=sn-uxanug5-cox6%2Csn-ntqe6n7r&ms=au%2Crdu&mv=m&mvi=6&pl=39&initcwndbps=1655000&mime=video%2Fmp4&ratebypass=yes&dur=917.768&lmt=1572418007364260&mt=1572474311&fvip=4&fexp=23842630&c=WEB&txp=5535432&sparams=expire%2Cei%2Cip%2Cid%2Citag%2Csource%2Crequiressl%2Cmime%2Cratebypass%2Cdur%2Clmt&sig=ALgxI2wwRgIhAIp-4gyUTLoXFetbY0ha_YnR7DJqsp_MNjjIxqDdfPZJAiEA_WPd21jgX9broBcigf8rcSEVoJb2_NX7t3XZQqytsSM%3D&lsparams=mm%2Cmn%2Cms%2Cmv%2Cmvi%2Cpl%2Cinitcwndbps&lsig=AHylml4wRAIgacvP3zjEq-rVEZFrX7a_hC6TR-Zab7Ii-Fbaupjs_PcCIHdZht4l4ioYL3ERz7WNiSbnOnhm5iYxEECaQXPP2hUp",
"video_title": "Arnold Schwarzenegger on Son-in-law Chris Pratt, Pranking Sylvester Stallone & Terminator’s Return",
"fmt_id": "22",
"fmt_quality": "1280x720"
},
{
"video_url": "https://r7---sn-uxanug5-cox6.googlevideo.com/videoplayback?expire=1572496003&ei=Iw66Xa24H8PL3LUPiN25mAs&ip=2001%3A8003%3A749b%3Aa01%3A5cd8%3Ac610%3A6402%3Ad0fe&id=o-ADsVnoOoBQ6-SWzYZU7gHES06s7xQptJG6hn9WcakITY&itag=18&source=youtube&requiressl=yes&mm=31%2C29&mn=sn-uxanug5-cox6%2Csn-ntqe6n7r&ms=au%2Crdu&mv=m&mvi=6&pl=39&initcwndbps=1655000&mime=video%2Fmp4&gir=yes&clen=44248820&ratebypass=yes&dur=917.768&lmt=1572416976690256&mt=1572474311&fvip=4&fexp=23842630&c=WEB&txp=5531432&sparams=expire%2Cei%2Cip%2Cid%2Citag%2Csource%2Crequiressl%2Cmime%2Cgir%2Cclen%2Cratebypass%2Cdur%2Clmt&sig=ALgxI2wwRQIhANTZJlBHFWQWCnfK11yvLiPUV26c6NzvqIMKjDwmsByMAiBUSy0ZJMo4GdHSiRU4xBDDLxLtzwKZAqAKCiB-1aViDQ%3D%3D&lsparams=mm%2Cmn%2Cms%2Cmv%2Cmvi%2Cpl%2Cinitcwndbps&lsig=AHylml4wRAIgacvP3zjEq-rVEZFrX7a_hC6TR-Zab7Ii-Fbaupjs_PcCIHdZht4l4ioYL3ERz7WNiSbnOnhm5iYxEECaQXPP2hUp",
"video_title": "Arnold Schwarzenegger on Son-in-law Chris Pratt, Pranking Sylvester Stallone & Terminator’s Return",
"fmt_id": "18",
"fmt_quality": "640x360"
}
]
But when I try and loop through each entry with fillInOptions(), my loop is never completed because the length is apparently zero. However, when I dump the array using console.log() it tells me the length is 2, and displays the above. I need to be able to add each option to my dropdown.
Thankyou!
UPDATE: Added full code, sorry!
It looks like your .forEach() is the root of the problem. The parameters of a forEach are currentValue, index like this: array.forEach(function(currentValue, index) {}); but it looks like you're using them in the opposite way
Try rewriting that iteration to this:
ytFill.forEach(function(v, i) {
console.log(i);
ytdlOptions.append(new Option(v.fmt_quality, v.fmt_id));
});
Notice the difference in the order of v and i in the parameters.

Remove event listening from body

I found this code for a slot machine and have been playing around with it. I'm having trouble removing the pull event from everything but the handle. Anybody see what I might be missing? I'm trying to enable a click trigger for some html but it also triggers the whole event from restarting. Any ideas on why that might be happening as well?
var fps = 60;
window.raf = (function(){
return requestAnimationFrame || webkitRequestAnimationFrame || mozRequestAnimationFrame || function(c){setTimeout(c,1000/fps);};
})();
/*--------------=== Slot machine definition ===--------------*/
(function() {
var NAME = "SlotMachine",
defaultSettings = {
width : "600",
height : "600",
colNum : 3,
rowNum : 9,
winRate : 50,
autoPlay : true,
autoSize : false,
autoPlayTime : 10,
layout : 'compact',
handleShow : true,
handleWidth : 35,
handleHeight : 30,
machineBorder : 15,
machineColor : 'rgba(120,60,30,1)',
names : [
"seven",
"lemon",
"cherry",
"watermelon",
"banana",
"bar",
"prune",
"bigwin",
"orange"
]
},
completed = true,
isShuffle = true,
supportTouch = 'ontouchstart' in window || navigator.msMaxTouchPoints,
firstTime = true,
nextLoop = null ;
SlotMachine = function (argument) {
this.init = this.init.bind(this);
this.run = this.run.bind(this);
this.addListener = this.addListener.bind(this);
this.beforeRun = this.beforeRun.bind(this);
this.afterRun = this.afterRun.bind(this);
this.showWin = this.showWin.bind(this);
this.rotateHandle = this.rotateHandle.bind(this);
this.colArr = [];
this.options = {};
}
SlotMachine.prototype.beforeRun = function(){
if (completed) {
this.showWin(false);
completed = false;
var result = null;
result = this.options.names[random(this.options.rowNum*100/this.options.winRate)|0];//set winrate
for(var i=0;i<this.options.colNum;i++){
this.colArr[i].beforeRun(result);
}
this.rotateHandle();
this.run();
}
if (this.options.autoPlay) nextLoop = setTimeout(function(){this.beforeRun()}.bind(this),this.options.autoPlayTime*1000);
}
SlotMachine.prototype.afterRun = function(){
completed = true;
var results = [],win=true;
for(var i=0;i<this.options.colNum;i++){
results.push(this.colArr[i].getResult());
if (i>0 && results[i]!=results[i-1]) {
win = false;
break;
}
}
if(win){
this.showWin(true);
setTimeout(function(){
this.showWin(false);
}.bind(this),this.options.autoPlayTime*1000);
}
}
SlotMachine.prototype.rotateHandle = function(){
var handle = document.querySelector(".handle");
if (handle) {
handle.addClass("active");
setTimeout(function(){
handle.removeClass("active");
},1000);
}
}
SlotMachine.prototype.run = function(){
var done = true;
for(var i=0;i<this.options.colNum;i++){
done &= this.colArr[i].run();
}
if (!done) raf(this.run)
else this.afterRun();
}
SlotMachine.prototype.showWin = function(show){
var winner = document.querySelector(".winner");
if (winner) winner.className= show ? "winner active" : "winner";
}
SlotMachine.prototype.init = function(){
//reset all
completed = true;
clearTimeout(nextLoop);
//get settings
var BannerFlow = arguments[0],
settingStyle = "",
machine = document.querySelector(".machine"),
container = document.querySelector(".container");
machine.style.opacity = 0;
for(var key in defaultSettings) {
this.options[key] = defaultSettings[key];
}
if (BannerFlow!==undefined){
var settings = BannerFlow.settings;
this.options.winRate = settings.winRate ? settings.winRate : defaultSettings.winRate;
this.options.autoPlay = settings.autoPlay;
this.options.colNum = settings.numberColumn ? settings.numberColumn : defaultSettings.colNum;
this.options.layout = settings.layout ? settings.layout : defaultSettings.layout;
this.options.machineColor = settings.machineColor ? settings.machineColor : defaultSettings.machineColor;
this.options.machineBorder = settings.machineBorder>=0 ? settings.machineBorder : defaultSettings.machineBorder;
this.options.height = settings.height ? settings.height : defaultSettings.height;
this.options.width = settings.width ? settings.width : defaultSettings.width;
this.options.autoSize = settings.autoSize;
if (this.options.autoSize) {
this.options.height = window.innerHeight;
this.options.width = window.innerWidth;
}
this.options.handleShow = settings.handleShow;
this.options.handleWidth = this.options.handleShow ? defaultSettings.handleWidth : 0;
this.options.autoPlayTime = settings.autoPlayTime ? settings.autoPlayTime : defaultSettings.autoPlayTime;
this.options.customImage = settings.customImage;
}
//apply settings
if (this.options.customImage){
var urls = BannerFlow.text.strip().split(",");
this.options.names = [];
for(var i=0;i<urls.length;i++){
var name = "image-"+i ; urls[i];
this.options.names.push(name);
settingStyle += getStyle("."+name+":after",{
"background-image" : "url('"+urls[i]+"')"
});
}
}
settingStyle += getStyle(".machine",{
"margin-top" : (window.innerHeight - this.options.height)/2 +"px",
"margin-left" : (window.innerWidth - this.options.width)/2 +"px"
});
settingStyle += getStyle(".container",{
"height" : this.options.height+"px",
"width" : this.options.width - this.options.handleWidth +"px",
"border-width" : this.options.machineBorder + "px",
"border-color" : this.options.machineColor + " " + getLighter(this.options.machineColor)
});
var winnerSize = 1.2*Math.max(this.options.height,this.options.width);
settingStyle += getStyle(".winner:before,.winner:after",{
"height" : winnerSize+"px",
"width" : winnerSize+"px",
"top" : (this.options.height-winnerSize)/2 - 20 + "px",
"left" : (this.options.width-winnerSize)/2 - this.options.handleWidth + "px"
});
settingStyle += getStyle(".handle",{
"margin-top" : this.options.height/2-this.options.handleHeight+"px"
});
document.querySelector("#setting").innerHTML = settingStyle;
//remove old cols
if (this.colArr && this.colArr.length > 0)
for (var i=0;i<this.colArr.length;i++){
container.removeChild(this.colArr[i].getDOM());
}
this.colArr = [];
// add new cols
for(var i=0;i<this.options.colNum;i++){
var col = new SlotColumn();
col.init(this.options.names.slice(0,this.options.rowNum),isShuffle);
this.colArr.push(col);
document.querySelector(".container").appendChild(col.getDOM());
}
machine.style.opacity = "1";
}
SlotMachine.prototype.addListener = function(){
var BannerFlow=arguments[0],timer,
that = this ,
container = document.querySelector(".container");
if (typeof BannerFlow!= 'undefined') {
// BannerFlow event
BannerFlow.addEventListener(BannerFlow.RESIZE, function() {
//clearTimeout(timer);
//timer = setTimeout(function(){that.init(BannerFlow);that.beforeRun()},500);
});
BannerFlow.addEventListener(BannerFlow.CLICK, function() {
that.beforeRun();
});
} else {
// Window event
window.addEventListener('resize', function(){
//clearTimeout(timer);
//timer = setTimeout(function(){that.init(BannerFlow);that.beforeRun()},500)
});
if (supportTouch) {
window.addEventListener("touchstart",function(){
that.beforeRun();
});
} else {
window.addEventListener("click",function(){
that.beforeRun();
});
}
}
var slotTrigger = document.querySelector("#slot-trigger");
if (slotTrigger) {
slotTrigger.addEventListener("click",function(e){
this.addClass('slot-triggerDown');
})
}
}
window[NAME]= SlotMachine;
})();
/*--------------=== Slot Column definition ===--------------*/
(function(){
var NAME = "SlotColumn";
SlotColumn = function(){
this.col = document.createElement("div");
this.col.className = "col";
this.init = this.init.bind(this);
this.run = this.run.bind(this);
this.beforeRun = this.beforeRun.bind(this);
this.getResult = this.getResult.bind(this);
this.getDOM = this.getDOM.bind(this);
this.arr = [];
this.colHeight=this.rowHeight=0;
this.loop = 2;
}
SlotColumn.prototype.init = function(){
this.col.empty();
this.arr=arguments[0];
var isShuffle=arguments[1];
if(isShuffle) shuffle(this.arr);
for(var i=0; i<this.arr.length*this.loop;i++){
var row = document.createElement("div");
row.className = "row "+this.arr[i%this.arr.length];
this.col.appendChild(row);
}
this.top = 0;
}
SlotColumn.prototype.beforeRun = function(){
this.halfHeight = this.col.offsetHeight/this.loop;
this.colHeight = this.col.scrollHeight/2;
this.rowHeight = this.colHeight/this.arr.length;
this.nextResult = arguments[0];
var next = this.arr.indexOf(this.nextResult);
if (next==-1) next=random(0,this.arr.length-1)|0;
var s = this.top + (random(2,10)|0)*this.colHeight + ((next+0.5)*this.rowHeight|0) - this.halfHeight;
var n = (random(2,6)|0) * fps;
this.speed = 2*s/(n+1);
this.acceleration = this.speed/n;
}
SlotColumn.prototype.getResult = function(){
var result = Math.ceil(((this.halfHeight-this.top)%this.colHeight)/this.rowHeight)-1;
//console.log(this.top,result,this.arr[result],this.halfHeight,this.colHeight,this.rowHeight);
return this.arr[result];
}
SlotColumn.prototype.run = function(){
if(this.speed <= 0) return true;//completed
this.top = (this.top - this.speed) % this.colHeight;
this.speed -= this.acceleration;
this.top %= this.colHeight;
this.col.style.transform = "translateY("+this.top+"px)";
return false;//not completed
}
SlotColumn.prototype.getDOM = function(){
return this.col;
}
window[NAME] = SlotColumn;
}());
/*--------------=== Utils definition ===--------------*/
//random in range
var random = function(){
var isNumeric = function(n){return !isNaN(parseFloat(n)) && isFinite(n)},
val = Math.random(),
arg = arguments;
return isNumeric(arg[0]) ? isNumeric(arg[1]) ? arg[0] + val*(arg[1] - arg[0]) : val*arg[0] : val;
};
//shuffle an array
var shuffle = function(arr){
var j,tmp;
for(var i=0;i<arr.length;i++){
j = random(arr.length)|0;
tmp = arr[i];arr[i]=arr[j];arr[j]=tmp;
}
}
//get CSS3 style
var setStyleCss3 = function (object, key, value) {
object.style['-webkit-'+ key] = value;
object.style['-moz-'+key] = value;
object.style['-ms-'+key] = value;
object.style[key] = value;
}
//get name from url
var getNameFromUrl = function(url){
if (url) {
var s=url.lastIndexOf("/")+1,e =url.lastIndexOf(".");
return s<e ? url.substring(s,e) : "";
}
return "";
}
//get style from object style
var getStyle = function(selector,styleObj){
var isAttribute = false;
var newStyle = selector+"{";
for(var attr in styleObj) {
if (styleObj[attr]) {
isAttribute = true;
newStyle += attr+" : "+styleObj[attr]+";";
}
}
newStyle+="}";
return isAttribute ? newStyle : "";
}
// get lighter color from rgba colors
var getLighter = function(rgba){
var o = /[^,]+(?=\))/g.exec(rgba)[0]*0.75;
return rgba.replace(/[^,]+(?=\))/g,o);
}
//remove html from text
if (!String.prototype.strip) {
String.prototype.strip = function() {
return this.replace(/(<[^>]+>)/ig," ").trim();
}
}
//remove all child node
if (!Node.prototype.empty) {
Node.prototype.empty = function(){
while (this.firstChild) {
this.removeChild(this.firstChild);
}
}
}
if (!HTMLElement.prototype.hasClass) {
Element.prototype.hasClass = function(c) {
return (" "+this.className+" ").replace(/[\n\t]/g, " ").indexOf(" "+c+" ") > -1;
}
}
if (!HTMLElement.prototype.addClass) {
HTMLElement.prototype.addClass = function(c) {
if (!this.hasClass(c)) this.className += (" " +c);
return this;
}
}
if (!HTMLElement.prototype.removeClass) {
HTMLElement.prototype.removeClass = function(c) {
if (this.hasClass(c)) this.className = (" "+this.className+" ").replace(" "+c+" "," ").trim();
return this;
}
}
/*--------------=== Main function ===--------------*/
var timer,widget = null;
if (typeof BannerFlow != 'undefined') {
BannerFlow.addEventListener(BannerFlow.SETTINGS_CHANGED, function() {
clearTimeout(timer);
timer = setTimeout(function(){
if (widget==null) {
widget = new SlotMachine();
widget.addListener(BannerFlow);
}
widget.init(BannerFlow);
widget.beforeRun();
},500);
});
}else {
window.addEventListener("load",function(e){
if (widget==null) {
widget = new SlotMachine();
widget.addListener();
}
widget.init();
widget.beforeRun();
})
}

Change select list to ul list.

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/

Javascript module programming

I'm study module programming.
take a look at below code:
var goodsspec = function(){
function setSpec(){
var
_price,
_storage,
defaultstats = true,
_val = '',
_resp = {
storage:".goods_stock",
price:".price"
}
$(".sys_item_spec .sys_item_specpara").each(function(){
var i = $(this);
var v = i.attr("data-attrval");
if(!v){
defaultstats = false;
}else{
val += _val!=""?"":"";
_val += v;
}
});
if(!!defaultstats){
_storage = sys_item['sys_attrprice'][_val]['goods_storage'];
_price = sys_item['sys_attrprice'][_val]['price'];
}else{
_storage = sys_item['goods_storage'];
_price = sys_item['price'];
}
$(_resp.storage).text( _storage);
$(_resp.price).text( _price);
if ( _storage == 0){
// Waring
}
}
return {
set:function(){
return setSpec();
}
};
}();
console.log(goodsspec.price);
I want to get _price and storage property value _value when I selected item.
How can I do this?
try something like
var Item = new Object();
function setSpec(){
// setting code
Item.price = _price;
Item.storage = _storage
}
then you could use
console.log("Prices is "+Item.price+" for "+Item.storage+".");

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 ','.

Categories

Resources