date sorting doesn't work in the datatable - javascript

I had a problem with the date sort, It didn't include the month while sorting, and sorted only by the day.
I solved it by adding the next code:
jQuery.extend( jQuery.fn.dataTableExt.oSort, {
"datetime-pre": function ( a ) {
var ukDatea = a.split('/');
return (ukDatea[2] + ukDatea[1] + ukDatea[0]) * 1;
},
"datetime-asc": function ( a, b ) {
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
},
"datetime-desc": function ( a, b ) {
return ((a < b) ? 1 : ((a > b) ? -1 : 0));
}
} );
var dt = $('#wires').DataTable({
"aoColumns": [
null,
null,
{ "sType": "datetime" },
{ "sType": "datetime" },
null,null,null,null,null,null,null,null,null,null,null,null,null,null
],
But now the column sorting (part of the datatable header) is not working only of one of the columns which include date.
Any advice/solutions?

What is the date format you're trying to sort?
I made functions to sort pt-BR date (dd/MM/yyyy) and datetime (dd/MM/yyyy HH:mm:ss). I had to convert the dates to integers in order to compare properly. For example: the date "25/03/2016" become the integer 20160325.
Take a look:
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
"br_datetime-asc": function (a, b) {
var x, y;
if (jQuery.trim(a) !== '') {
var deDatea = jQuery.trim(a).split(' ');
var deTimea = deDatea[1].split(':');
var deDatea2 = deDatea[0].split('/');
if (typeof deTimea[2] !== 'undefined') {
x = (deDatea2[2] + deDatea2[1] + deDatea2[0] + deTimea[0] + deTimea[1] + deTimea[2]) * 1;
} else {
x = (deDatea2[2] + deDatea2[1] + deDatea2[0] + deTimea[0] + deTimea[1]) * 1;
}
} else {
x = Infinity; // = l'an 1000 ...
}
if (jQuery.trim(b) !== '') {
var deDateb = jQuery.trim(b).split(' ');
var deTimeb = deDateb[1].split(':');
deDateb = deDateb[0].split('/');
if (typeof deTimeb[2] !== 'undefined') {
y = (deDateb[2] + deDateb[1] + deDateb[0] + deTimeb[0] + deTimeb[1] + deTimeb[2]) * 1;
} else {
y = (deDateb[2] + deDateb[1] + deDateb[0] + deTimeb[0] + deTimeb[1]) * 1;
}
} else {
y = Infinity;
}
var z = ((x < y) ? -1 : ((x > y) ? 1 : 0));
return z;
},
"br_datetime-desc": function (a, b) {
var x, y;
if (jQuery.trim(a) !== '') {
var deDatea = jQuery.trim(a).split(' ');
var deTimea = deDatea[1].split(':');
var deDatea2 = deDatea[0].split('/');
if (typeof deTimea[2] !== 'undefined') {
x = (deDatea2[2] + deDatea2[1] + deDatea2[0] + deTimea[0] + deTimea[1] + deTimea[2]) * 1;
} else {
x = (deDatea2[2] + deDatea2[1] + deDatea2[0] + deTimea[0] + deTimea[1]) * 1;
}
} else {
x = Infinity;
}
if (jQuery.trim(b) !== '') {
var deDateb = jQuery.trim(b).split(' ');
var deTimeb = deDateb[1].split(':');
deDateb = deDateb[0].split('/');
if (typeof deTimeb[2] !== 'undefined') {
y = (deDateb[2] + deDateb[1] + deDateb[0] + deTimeb[0] + deTimeb[1] + deTimeb[2]) * 1;
} else {
y = (deDateb[2] + deDateb[1] + deDateb[0] + deTimeb[0] + deTimeb[1]) * 1;
}
} else {
y = Infinity;
}
var z = ((x < y) ? 1 : ((x > y) ? -1 : 0));
return z;
},
"br_date-asc": function (a, b) {
var x, y;
if (jQuery.trim(a) !== '') {
var deDatea = jQuery.trim(a).split('/');
x = (deDatea[2] + deDatea[1] + deDatea[0]) * 1;
} else {
x = Infinity; // = l'an 1000 ...
}
if (jQuery.trim(b) !== '') {
var deDateb = jQuery.trim(b).split('/');
y = (deDateb[2] + deDateb[1] + deDateb[0]) * 1;
} else {
y = Infinity;
}
var z = ((x < y) ? -1 : ((x > y) ? 1 : 0));
return z;
},
"br_date-desc": function (a, b) {
var x, y;
if (jQuery.trim(a) !== '') {
var deDatea = jQuery.trim(a).split('/');
x = (deDatea[2] + deDatea[1] + deDatea[0]) * 1;
} else {
x = Infinity;
}
if (jQuery.trim(b) !== '') {
var deDateb = jQuery.trim(b).split('/');
y = (deDateb[2] + deDateb[1] + deDateb[0]) * 1;
} else {
y = Infinity;
}
var z = ((x < y) ? 1 : ((x > y) ? -1 : 0));
return z;
}
});
Edit:
And in the columnDefs you should set br_datetime or br_date. Or maybe use the type-detection plugin (https://datatables.net/plug-ins/type-detection/) with custom functions:
jQuery.fn.dataTableExt.aTypes.unshift(
function (sData) {
if (sData !== null && typeof sData !== 'string') {
sData = sData.toString();
}
if (sData !== null && sData.match(/^(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[012])\/(19|20|21)\d\d$/)) {
return 'br_date';
}
else if (sData !== null && sData.match(/^(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[012])\/(19|20|21)\d\d [0-9]{2}:[0-9]{2}(:[0-9]{2})?$/)) {
return 'br_datetime';
}
return null;
}
);

Related

How to add factorial calculation to a WordPress plugin by JavaScript?

I want to add factorial (n!) calculation to Calculated Fields Form WordPress plugin. I found out that module_public.js (in this direction: wp-content\plugins\calculated-fields-form\js\modules\01_mathematical_logical\public) contains the code for math operations and I added these codes, but they did not work (I can make a button for factorial by adding code to module_admin.js and the button works but I can't get the result).
Can anyone help me?
My codes that I added to line 209 in module_public.js:
if(window.FAC == undefined)
{
window.FAC = window.fac = function ()
{
var ans=1;
for (var i = 2; i <= FAC; i++)
ans = ans * i;
return ans;
};
} // End if window.FAC
original code of module_public.js:
fbuilderjQuery = ( typeof fbuilderjQuery != 'undefined' ) ? fbuilderjQuery : jQuery;
fbuilderjQuery[ 'fbuilder' ] = f
builderjQuery[ 'fbuilder' ] || {};
fbuilderjQuery[ 'fbuilder' ][ 'modules' ] = fbuilderjQuery[ 'fbuilder' ][ 'mo
dules' ] || {};
fbuilderjQuery[ 'fbuilder' ][ 'modules' ][ 'default' ] = {
'prefix' : '',
'callback' : function()
{
if(Number.prototype.LENGTH == undefined)
{
// Only LENGTH in uppercase to prevent a conflict with Lottie
Number.prototype.LENGTH = function(){return this.valueOf().toString().length;};
}
function ROUNDx(operation, num, y)
{
if(y && y != 0)
{
var r = operation(num/y)*y, p = (new String(y)).split('.');
if(p.length == 2) r = PREC(r,p[1].length);
return r;
}
else
{
return operation(num);
}
};
if(window.ROUND == undefined)
{
window.ROUND = window.round = function(num, y)
{
if(y) return ROUNDx(Math.round, num, y);
return ROUNDx(Math.round, num);
}
}
if(window.FLOOR == undefined)
{
window.FLOOR = window.floor = function(num, y)
{
if(y) return ROUNDx(Math.floor, num, y);
return ROUNDx(Math.floor, num);
}
}
if(window.CEIL == undefined)
{
window.CEIL = window.ceil = function(num, y)
{
if(y) return ROUNDx(Math.ceil, num, y);
return ROUNDx(Math.ceil, num);
}
}
if(window.PREC == undefined)
{
window.PREC = window.prec = function (num, pr)
{
if('undefined' == typeof pr) pr = 0;
if(/^\d+$/.test(pr) && $.isNumeric(num))
{
var f = POW(10,pr);
num = ROUND(num*f)/f;
return num.toFixed(pr);
}
return num;
};
} // End if window.PREC
if(window.CDATE == undefined)
{
window.CDATE = window.cdate = function ( num, format )
{
format = ( typeof format != 'undefined' ) ? format : ( ( typeof window.DATETIMEFORMAT != 'undefined' ) ? window.DATETIMEFORMAT : 'dd/mm/yyyy' );
if(isFinite(num*1))
{
num = Math.round(num*86400000);
var date = new Date(num),
d = date.getDate(),
m = date.getMonth()+1,
y = date.getFullYear(),
h = date.getHours(),
i = date.getMinutes(),
s = date.getSeconds(),
a = '';
m = (m < 10) ? '0'+m : m;
d = (d < 10) ? '0'+d : d;
if( /a/.test( format ) )
{
a = ( h >= 12 ) ? 'pm' : 'am';
h = h % 12;
h = ( h == 0 ) ? 12: h;
}
h = (h < 10) ? '0'+h : h;
i = (i < 10) ? '0'+i : i;
s = (s < 10) ? '0'+s : s;
return format.replace( /y+/i, y)
.replace( /m+/i, m)
.replace( /d+/i, d)
.replace( /h+/i, h)
.replace( /i+/i, i)
.replace( /s+/i, s)
.replace( /a+/i, a);
}
return num;
};
} // End if window.CDATE
if(window.SUM == undefined)
{
window.SUM = window.sum = function ()
{
var r = 0, t;
for(var i in arguments)
{
if(Array.isArray(arguments[i])) r += SUM.apply(this,arguments[i]);
else
{
t = arguments[i]*1;
if(!isNaN(t)) r += t;
}
}
return r;
};
} // End if window.SUM
if(window.CONCATENATE == undefined)
{
window.CONCATENATE = window.concatenate = function ()
{
var r = '';
for(var i in arguments)
if(Array.isArray(arguments[i])) r += CONCATENATE.apply(this,arguments[i]);
else r += (new String(arguments[i]));
return r;
};
} // End if window.CONCATENATE
if(window.AVERAGE == undefined)
{
window.AVERAGE = window.average = function ()
{
return SUM.apply(this,arguments)/arguments.length;
};
} // End if window.AVERAGE
if(window.GCD == undefined)
{
window.GCD = window.gcd = function( a, b)
{
if ( ! b) return a;
return GCD(b, a % b);
};
} // End if window.GCD
if(window.LCM == undefined)
{
window.LCM = window.lcm = function( a, b)
{
return (!a || !b) ? 0 : ABS((a * b) / GCD(a, b));
};
} // End if window.LCM
if(window.LOGAB == undefined)
{
window.LOGAB = window.logab = function( a, b)
{
return LOG(a)/LOG(b);
};
} // End if window.LOGAB
var math_prop = ["LN10", "PI", "E", "LOG10E", "SQRT2", "LOG2E", "SQRT1_2", "LN2", "cos", "pow", "log", "tan", "sqrt", "asin", "abs", "exp", "atan2", "atanh", "random", "acos", "atan", "sin"];
for(var i = 0, h = math_prop.length; i < h; i++)
{
if( !window[ math_prop[ i ] ] )
{
window[ math_prop[ i ] ] = window[ math_prop[ i ].toUpperCase() ] = Math[ math_prop[ i ] ];
}
}
if(window.MIN == undefined)
{
window.MIN = window.min = function ()
{
var l = [];
for(var i in arguments)
var l = l.concat(arguments[i]);
return Math.min.apply(this, l);
};
} // End if window.MIN
if(window.MAX == undefined)
{
window.MAX = window.max = function ()
{
var l = [];
for(var i in arguments)
var l = l.concat(arguments[i]);
return Math.max.apply(this, l);
};
} // End if window.MAX
if(window.RADIANS == undefined)
{
window.RADIANS = window.radians = function(a){ return a*PI/180;};
}
if(window.DEGREES == undefined)
{
window.DEGREES = window.degrees = function(a){ return a*180/PI;};
}
fbuilderjQuery[ 'fbuilder' ][ 'extend_window' ]( fbuilderjQuery[ 'fbuilder' ][ 'modules' ][ 'default' ][ 'prefix' ], CF_LOGICAL );
},
'validator' : function( v )
{
return ( typeof v == 'number' ) ? isFinite( v ) : ( typeof v != 'undefined' );
}
};
try to paste the code below!
fbuilderjQuery = ( typeof fbuilderjQuery != 'undefined' ) ? fbuilderjQuery : jQuery;
fbuilderjQuery[ 'fbuilder' ] = f
builderjQuery[ 'fbuilder' ] || {};
fbuilderjQuery[ 'fbuilder' ][ 'modules' ] = fbuilderjQuery[ 'fbuilder' ][ 'mo
dules' ] || {};
fbuilderjQuery[ 'fbuilder' ][ 'modules' ][ 'default' ] = {
'prefix' : '',
'callback' : function()
{
if(Number.prototype.LENGTH == undefined)
{
// Only LENGTH in uppercase to prevent a conflict with Lottie
Number.prototype.LENGTH = function(){return this.valueOf().toString().length;};
}
function ROUNDx(operation, num, y)
{
if(y && y != 0)
{
var r = operation(num/y)*y, p = (new String(y)).split('.');
if(p.length == 2) r = PREC(r,p[1].length);
return r;
}
else
{
return operation(num);
}
};
if(window.ROUND == undefined)
{
window.ROUND = window.round = function(num, y)
{
if(y) return ROUNDx(Math.round, num, y);
return ROUNDx(Math.round, num);
}
}
if(window.FLOOR == undefined)
{
window.FLOOR = window.floor = function(num, y)
{
if(y) return ROUNDx(Math.floor, num, y);
return ROUNDx(Math.floor, num);
}
}
if(window.CEIL == undefined)
{
window.CEIL = window.ceil = function(num, y)
{
if(y) return ROUNDx(Math.ceil, num, y);
return ROUNDx(Math.ceil, num);
}
}
if(window.PREC == undefined)
{
window.PREC = window.prec = function (num, pr)
{
if('undefined' == typeof pr) pr = 0;
if(/^\d+$/.test(pr) && $.isNumeric(num))
{
var f = POW(10,pr);
num = ROUND(num*f)/f;
return num.toFixed(pr);
}
return num;
};
} // End if window.PREC
if(window.CDATE == undefined)
{
window.CDATE = window.cdate = function ( num, format )
{
format = ( typeof format != 'undefined' ) ? format : ( ( typeof window.DATETIMEFORMAT != 'undefined' ) ? window.DATETIMEFORMAT : 'dd/mm/yyyy' );
if(isFinite(num*1))
{
num = Math.round(num*86400000);
var date = new Date(num),
d = date.getDate(),
m = date.getMonth()+1,
y = date.getFullYear(),
h = date.getHours(),
i = date.getMinutes(),
s = date.getSeconds(),
a = '';
m = (m < 10) ? '0'+m : m;
d = (d < 10) ? '0'+d : d;
if( /a/.test( format ) )
{
a = ( h >= 12 ) ? 'pm' : 'am';
h = h % 12;
h = ( h == 0 ) ? 12: h;
}
h = (h < 10) ? '0'+h : h;
i = (i < 10) ? '0'+i : i;
s = (s < 10) ? '0'+s : s;
return format.replace( /y+/i, y)
.replace( /m+/i, m)
.replace( /d+/i, d)
.replace( /h+/i, h)
.replace( /i+/i, i)
.replace( /s+/i, s)
.replace( /a+/i, a);
}
return num;
};
} // End if window.CDATE
if(window.SUM == undefined)
{
window.SUM = window.sum = function ()
{
var r = 0, t;
for(var i in arguments)
{
if(Array.isArray(arguments[i])) r += SUM.apply(this,arguments[i]);
else
{
t = arguments[i]*1;
if(!isNaN(t)) r += t;
}
}
return r;
};
} // End if window.SUM
if(window.CONCATENATE == undefined)
{
window.CONCATENATE = window.concatenate = function ()
{
var r = '';
for(var i in arguments)
if(Array.isArray(arguments[i])) r += CONCATENATE.apply(this,arguments[i]);
else r += (new String(arguments[i]));
return r;
};
} // End if window.CONCATENATE
if(window.AVERAGE == undefined)
{
window.AVERAGE = window.average = function ()
{
return SUM.apply(this,arguments)/arguments.length;
};
} // End if window.AVERAGE
if(window.GCD == undefined)
{
window.GCD = window.gcd = function( a, b)
{
if ( ! b) return a;
return GCD(b, a % b);
};
} // End if window.GCD
if(window.LCM == undefined)
{
window.LCM = window.lcm = function( a, b)
{
return (!a || !b) ? 0 : ABS((a * b) / GCD(a, b));
};
} // End if window.LCM
if(window.LOGAB == undefined)
{
window.LOGAB = window.logab = function( a, b)
{
return LOG(a)/LOG(b);
};
} // End if window.LOGAB
var math_prop = ["LN10", "PI", "E", "LOG10E", "SQRT2", "LOG2E", "SQRT1_2", "LN2", "cos", "pow", "log", "tan", "sqrt", "asin", "abs", "exp", "atan2", "atanh", "random", "acos", "atan", "sin"];
for(var i = 0, h = math_prop.length; i < h; i++)
{
if( !window[ math_prop[ i ] ] )
{
window[ math_prop[ i ] ] = window[ math_prop[ i ].toUpperCase() ] = Math[ math_prop[ i ] ];
}
}
if(window.MIN == undefined)
{
window.MIN = window.min = function ()
{
var l = [];
for(var i in arguments)
var l = l.concat(arguments[i]);
return Math.min.apply(this, l);
};
} // End if window.MIN
if(window.MAX == undefined)
{
window.MAX = window.max = function ()
{
var l = [];
for(var i in arguments)
var l = l.concat(arguments[i]);
return Math.max.apply(this, l);
};
} // End if window.MAX
if(window.FAC == undefined)
{
window.FAC = window.fac = function (num)
{
let sm=num;
if(num == 0)
return 1;
else{
for(let i=num-1; i>=1; i--){
sm *= (num-i);
console.log(sm);
}
return sm;
}
if(window.RADIANS == undefined)
{
window.RADIANS = window.radians = function(a){ return a*PI/180;};
}
if(window.DEGREES == undefined)
{
window.DEGREES = window.degrees = function(a){ return a*180/PI;};
}
fbuilderjQuery[ 'fbuilder' ][ 'extend_window' ]( fbuilderjQuery[ 'fbuilder' ][ 'modules' ][ 'default' ][ 'prefix' ], CF_LOGICAL );
},
'validator' : function( v )
{
return ( typeof v == 'number' ) ? isFinite( v ) : ( typeof v != 'undefined' );
}
};

how to modify below function to read 3 decimal places

I am using tafgeet javascript function to convert numbers into Arabic words, but the problem is that it supports only 2 decimal places, how can I modify the function to make it read 3 decimal places:
It actually translates upto a million on the left hand side, so it would be possible to apply the same methodology on the right side.
I tried to fiddle with it, but it doesn't work. I am posting the original javascript.
/**
* TafgeetJS module.
* #module TafgeetJS
* #description Converts currency digits into written Arabic words
* #author Mohammed Mahgoub <mmahgoub#gmail.com>
*/
function Tafgeet(digit) {
var currency = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "SDG";
//Split fractions
var splitted = digit.toString().split(".");
this.fraction = 0;
if (splitted.length > 1) {
var fraction = parseInt(splitted[1]);
if (fraction >= 1 && fraction <= 99) {
this.fraction = splitted[1].length === 1 ? fraction * 10 : fraction;
} else {
//trim it
var trimmed = Array.from(splitted[1]);
this.fraction = "" + trimmed[0] + trimmed[1];
}
}
this.digit = splitted[0];
this.currency = currency;
}
Tafgeet.prototype.parse = function () {
var serialized = [];
var tmp = [];
var inc = 1;
var count = this.length();
var column = this.getColumnIndex();
if (count >= 16) {
console.error("Number out of range!");
return;
}
//Sperate the number into columns
Array.from(this.digit.toString()).reverse().forEach(function (d, i) {
tmp.push(d);
if (inc == 3) {
serialized.unshift(tmp);
tmp = [];
inc = 0;
}
if (inc == 0 && count - (i + 1) < 3 && count - (i + 1) != 0) {
serialized.unshift(tmp);
}
inc++;
});
// Generate concatenation array
var concats = []
for (i = this.getColumnIndex(); i < this.columns.length; i++) {
concats[i] = " و";
}
//We do not need some "و"s check last column if 000 drill down until otherwise
if (this.digit > 999) {
if (parseInt(Array.from(serialized[serialized.length - 1]).join("")) == 0) {
concats[parseInt(concats.length - 1)] = ""
for (i = serialized.length - 1; i >= 1; i--) {
if (parseInt(Array.from(serialized[i]).join("")) == 0) {
concats[i] = ""
} else {
break;
}
}
}
}
var str = "";
str += "فقط ";
if (this.length() >= 1 && this.length() <= 3) {
str += this.read(this.digit);
} else {
for (i = 0; i < serialized.length; i++) {
var joinedNumber = parseInt(serialized[i].reverse().join(""));
if (joinedNumber == 0) {
column++;
continue;
}
if (column == null || column + 1 > this.columns.length) {
str += this.read(joinedNumber);
} else {
str += this.addSuffixPrefix(serialized[i], column) + concats[column];
}
column++;
}
}
if (this.currency != "") {
if (this.digit >= 3 && this.digit <= 10) {
str += " " + this.currencies[this.currency].plural;
} else {
str += " " + this.currencies[this.currency].singular;
}
if (this.fraction != 0) {
if (this.digit >= 3 && this.digit <= 10) {
str +=
" و" +
this.read(this.fraction) +
" " +
this.currencies[this.currency].fractions;
} else {
str +=
" و" +
this.read(this.fraction) +
" " +
this.currencies[this.currency].fraction;
}
}
}
str += " لا غير";
return str;
};
Tafgeet.prototype.addSuffixPrefix = function (arr, column) {
if (arr.length == 1) {
if (parseInt(arr[0]) == 1) {
return this[this.columns[column]].singular;
}
if (parseInt(arr[0]) == 2) {
return this[this.columns[column]].binary;
}
if (parseInt(arr[0]) > 2 && parseInt(arr[0]) <= 9) {
return (
this.readOnes(parseInt(arr[0])) +
" " +
this[this.columns[column]].plural
);
}
} else {
var joinedNumber = parseInt(arr.join(""));
if (joinedNumber > 1) {
return this.read(joinedNumber) + " " + this[this.columns[column]].singular;
} else {
return this[this.columns[column]].singular;
}
}
};
Tafgeet.prototype.read = function (d) {
var str = "";
var len = Array.from(d.toString()).length;
if (len == 1) {
str += this.readOnes(d);
} else if (len == 2) {
str += this.readTens(d);
} else if (len == 3) {
str += this.readHundreds(d);
}
return str;
};
Tafgeet.prototype.readOnes = function (d) {
if (d == 0) return;
return this.ones["_" + d.toString()];
};
Tafgeet.prototype.readTens = function (d) {
if (Array.from(d.toString())[1] === "0") {
return this.tens["_" + d.toString()];
}
if (d > 10 && d < 20) {
return this.teens["_" + d.toString()];
}
if (d > 19 && d < 100 && Array.from(d.toString())[1] !== "0") {
return (
this.readOnes(Array.from(d.toString())[1]) +
" و" +
this.tens["_" + Array.from(d.toString())[0] + "0"]
);
}
};
Tafgeet.prototype.readHundreds = function (d) {
var str = "";
str += this.hundreds["_" + Array.from(d.toString())[0] + "00"];
if (
Array.from(d.toString())[1] === "0" &&
Array.from(d.toString())[2] !== "0"
) {
str += " و" + this.readOnes(Array.from(d.toString())[2]);
}
if (Array.from(d.toString())[1] !== "0") {
str +=
" و" +
this.readTens(
(Array.from(d.toString())[1] + Array.from(d.toString())[2]).toString()
);
}
return str;
};
Tafgeet.prototype.length = function () {
return Array.from(this.digit.toString()).length;
};
Tafgeet.prototype.getColumnIndex = function () {
var column = null;
if (this.length() > 12) {
column = 0;
} else if (this.length() <= 12 && this.length() > 9) {
column = 1;
} else if (this.length() <= 9 && this.length() > 6) {
column = 2;
} else if (this.length() <= 6 && this.length() >= 4) {
column = 3;
}
return column;
};
Tafgeet.prototype.ones = {
_1: "واحد",
_2: "ٱثنين",
_3: "ثلاثة",
_4: "أربعة",
_5: "خمسة",
_6: "ستة",
_7: "سبعة",
_8: "ثمانية",
_9: "تسعة"
};
Tafgeet.prototype.teens = {
_11: "أحد عشر",
_12: "أثني عشر",
_13: "ثلاثة عشر",
_14: "أربعة عشر",
_15: "خمسة عشر",
_16: "ستة عشر",
_17: "سبعة عشر",
_18: "ثمانية عشر",
_19: "تسعة عشر"
};
Tafgeet.prototype.tens = {
_10: "عشرة",
_20: "عشرون",
_30: "ثلاثون",
_40: "أربعون",
_50: "خمسون",
_60: "ستون",
_70: "سبعون",
_80: "ثمانون",
_90: "تسعون"
};
Tafgeet.prototype.hundreds = {
_100: "مائة",
_200: "مائتين",
_300: "ثلاثمائة",
_400: "أربعمائة",
_500: "خمسمائة",
_600: "ستمائة",
_700: "سبعمائة",
_800: "ثمانمائة",
_900: "تسعمائة"
};
Tafgeet.prototype.thousands = {
singular: "ألف",
binary: "ألفين",
plural: "ألآف"
};
Tafgeet.prototype.milions = {
singular: "مليون",
binary: "مليونين",
plural: "ملايين"
};
Tafgeet.prototype.bilions = {
singular: "مليار",
binary: "مليارين",
plural: "مليارات"
};
Tafgeet.prototype.trilions = {
singular: "ترليون",
binary: "ترليونين",
plural: "ترليونات"
};
Tafgeet.prototype.columns = ["trilions", "bilions", "milions", "thousands"];
Tafgeet.prototype.currencies = {
SDG: {
singular: "جنيه سوداني",
plural: "جنيهات سودانية",
fraction: "قرش",
fractions: "قروش"
},
SAR: {
singular: "ريال سعودي",
plural: "ريالات سعودية",
fraction: "هللة",
fractions: "هللات"
},
QAR: {
singular: "ريال قطري",
plural: "ريالات قطرية",
fraction: "درهم",
fractions: "دراهم"
},
AED: {
singular: "درهم أماراتي",
plural: "دراهم أماراتية",
fraction: "فلس",
fractions: "فلوس"
},
EGP: {
singular: "جنيه مصري",
plural: "جنيهات مصرية",
fraction: "قرش",
fractions: "قروش"
},
USD: {
singular: "دولار أمريكي",
plural: "دولارات أمريكية",
fraction: "سنت",
fractions: "سنتات"
},
AUD: {
singular: "دولار أسترالي",
plural: "دولارات أسترالية",
fraction: "سنت",
fractions: "سنتات"
},
TND: {
singular: "دينار تونسي",
plural: "دنانير تونسية",
fraction: "مليم",
fractions: "مليمات"
}
};
module.exports = Tafgeet;
Thanks.
Change this:
this.fraction = "" + trimmed[0] + trimmed[1];
To this:
this.fraction = "" + trimmed[0] + trimmed[1] + trimmed[2];
But this is a crude solution you need to do some validations and checks before you deploy this to production

equations with 3 numbers not displaying on HTML

I'm writing a math problem generator, but when I run it only equations with 2 numbers are displayed, anything more and it says "undefined" and refuses to show the answer. Here is the entire code(please note it is incomplete right now)
var type = 0;
var ans = 0;
function generatenumeral() {
var num = (Math.round(1000 * Math.random())) / 100;
var abs = Math.random();
if (abs < .4) {
num = num * -1;
}
console.log(num);
return (num);
}
function generatelength() {
var num = (Math.ceil(3 * Math.random()));
console.log(num);
return (num);
}
function generateSymbol() {
var sign = 0;
var num = (Math.round(12 * Math.random()));
console.log(num);
if (num === 0 || num == 1 || num == 9) {
sign = "+";
};
if (num === 2 || num == 3 || num == 10) {
sign = "-";
};
if (num === 4 || num == 5 || num == 11) {
sign = "/";
};
if (num === 6 || num == 7 || num == 12) {
sign = "*";
};
if (num == 8) {
sign = "+";
};
return (sign);
}
function WarmUpAr() {
var leng = generatelength();
if (leng == 1) {
var cool = twoNumb();
return (cool);
}
if (leng == 2) {
var cool = threNumb();
return (cool);
}
function twoNumb() {
var sign = 0;
var equation = 0;
var a = generatenumeral();
var b = generatenumeral();
var siggn = generateSymbol();
equation = a + " " + siggn + " " + b;
if (siggn == "+") {
ans = a + b;
}
if (siggn == "-") {
ans = a - b;
}
if (siggn == "/") {
ans = a / b;
}
if (siggn == "*") {
ans = a * b;
}
return (equation);
}
function threNumb() {
var sign = 0;
var a = generatenumeral();
var b = generatenumeral();
var c = generatenumeral();
var siggn = generateSymbol();
var siggnA = generateSymbol();
var equation = a + " " + siggn + " " + b +" "+ siggnA +" "+ c;
if (siggn.equals("+")) {
if (siggna.equals("+")) {
ans = a + b + c;
}
if (siggna.equals("-")) {
ans = (a + b) - c;
}
if (siggna.equals("/")) {
ans = a + (b / c);
}
if (siggna.equals("*")) {
ans = a + (b * c);
}
}
if (siggn.equals("-")) {
if (siggna.equals("+")) {
ans = a - b + c;
}
if (siggna.equals("-")) {
ans = (a - b) - c;
}
if (siggna == "/") {
ans = a - (b / c);
}
if (siggna.equals("*")) {
ans = a - (b * c);
}
}
if (siggn.equals("/")) {
if (siggna.equals("+")) {
ans = (a / b) + c;
}
if (siggna.equals("-")) {
ans = (a / b) - c;
}
if (siggna.equals("/")) {
ans = (a / b) / c;
}
if (siggna.equals("*")) {
ans = (a / b) * c;
}
}
if (siggn.equals("*")) {
if (siggna.equals("+")) {
ans = (a * b) + c;
}
if (siggna.equals("-")) {
ans = (a * b) - c;
}
if (siggna.equals("/")) {
ans = (a * b) / c;
}
if (siggna.equals("*")) {
ans = (a * b) * c;
}
}
// if (siggn == "^") {
// var ba = Math.round(b);
// var count = 0;
// for (count = 0; count < ba; count += 1) {
// var ab = ab * a;
// }
// ans = ab;
return (equation);
}
document.getElementById("ans").innerHTML = "not yet";
function arithmetic() {
type = 1;
document.getElementById("demo").innerHTML = WarmUpAr();
}
function preAlg() {
type = 2;
document.getElementById("demo").innerHTML = "hello";
}
function Alg() {
type = 3;
document.getElementById("demo").innerHTML = "This is cool";
}
function theAns() {
document.getElementById("ans").innerHTML = ans;
}
<p> "your warm up is....." </p>
<button onclick="arithmetic()">Arithmetic Warm Up </button>
<button onclick="preAlg()">PreAlg Warm Up </button>
<button onclick="Alg()">Algerbra Warm Up </button>
<p id="demo"></p>
<p>the answer is ....</p>
<button onclick="theAns()">answer</button>
<p id="ans"></p>
You forgot to close the WarmUpAr funtion,that's why you are getting undefined error
close this function WarmUpAr();
function WarmUpAr() {
var leng = generatelength();
if (leng == 1) {
var cool = twoNumb();
return (cool);
}
if (leng == 2) {
var cool = threNumb();
return (cool);
}
}
The reason threNumb() is failing is because your calling siggna.equals() in all your if statements. twoNumb() works because your using == instead of equals().
Also, in terms of calculating the answer to the equation, your doing it the hard way. In twoNumb() and threNumb() everything between where you set the 'equation' variable and where you return the 'equation' can be replaced with:
ans = eval(equation);

JavaScript function to transform a currency field in words

i found several scripts to do this with ENG/US currency, but I need it in Portuguese language, and its getting hard to find.
I've tried to modify a script to my needs but it is hard.
So, I found this script on web but it dont work too. What is wrong? Uncaught SyntaxError: Unexpected identifier : lin23
<script>
function number_format(a, b, c, d) {
a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
e = a + '';
f = e.split('.');
if (!f[0]) {
f[0] = '0';
}
if (!f[1]) {
f[1] = '';
}
if (f[1].length < b) {
g = f[1];
for (i=f[1].length + 1; i <= b; i++) {
g += '0';
}
f[1] = g;
}
if(d != '' && f[0].length > 3) {
h = f[0];
f[0] = '';
for(j = 3; j < h.length; j+=3) {
i = h.slice(h.length – j, h.length – j + 3);
f[0] = d + i + f[0] + '';
}
j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
f[0] = j + f[0];
}
c = (b <= 0) ? '' : c;
return f[0] + c + f[1];
}
function ValorPorExtenso(valor) {
if (!valor) return 'Zero';
var singular = ["centavo", "real", "mil", "milhão", "bilhão", "trilhão", "quatrilhão"];
var plural = ["centavos", "reais", "mil", "milhões", "bilhões", "trilhões", "quatrilhões"];
var c = ["", "cento", "duzentos", "trezentos", "quatrocentos", "quinhentos", "seiscentos", "setecentos", "oitocentos", "novecentos"];
var d = ["", "dez", "vinte", "trinta", "quarenta", "cinquenta", "sessenta", "setenta", "oitenta", "noventa"];
var d10 = ["dez", "onze", "doze", "treze", "quatorze", "quinze", "dezesseis", "dezesete", "dezoito", "dezenove"];
var u = ["", "um", "dois", "três", "quatro", "cinco", "seis", "sete", "oito", "nove"];
var z = 0;
valor = valor.toString();
valor = number_format(valor, 2, '.', '.');
alert(valor);
var inteiro = valor.split(/\./);
for (var i = 0; i < inteiro.length; i++) {
inteiro[i] = inteiro[i].toString();
for (var ii = inteiro[i].length; ii < 3; ii++) {
inteiro[i] = '0' + inteiro[i];
}
}
var fim = inteiro.length – ( inteiro[inteiro.length-1] > 0 ? 1 : 2 );
var rc, rd, ru;
var r, t;
var rt = '';
var valor_split;
for (var i = 0; i < inteiro.length; i++) {
valor = inteiro[i];
valor_split = valor.match(/./g);
rc = ((valor > 100) && (valor < 200)) ? 'cento' : c[valor_split[0]];
rd = (valor_split[1] < 2) ? '' : d[valor_split[1]];
ru = (valor > 0) ? ((valor_split[1] == 1) ? d10[valor_split[2]] : u[valor_split[2]]) : '';
r = rc + ((rc && (rd || ru)) ? ' e ' : '') + rd + ((rd && ru) ? ' e ' : '') + ru;
t = inteiro.length – 1 – i;
r = r + (r ? ' ' + (valor > 1 ? plural[t] : singular[t]) : '');
if (valor == '000') z++;
else if (z > 0) z–;
if ((t==1) && (z>0) && (inteiro[0] > 0)) {
r = r + ((z>1) ? ' de ' : '') + plural[t];
}
if (r) {
rt = rt + (((i > 0) && (i <= fim) && (inteiro[0] > 0) && (z < 1)) ? ( (i < fim) ? ', ' : ' e ') : ' ') + r;
}
}
return (rt ? rt : 'zero');
}
alert(ValorPorExtenso(8916165));
</script>
I realize that you copied the code as is and pasted into a seperate file. There is a problem with the encoding of some characters. For example, so '-' are incorrectly encoded; so just replace them
i = h.slice(h.length – j, h.length – j + 3)
should be
i = h.slice(h.length - j, h.length – j + 3)
I know you can't see the difference, but the two characters are different.
Have a look at the modified code: http://jsfiddle.net/7P3Vy/

adding autoplay to jquery.roundabout

I have a site I am working on that uses the roundabout from fredhq.com and I would like to make it so it auto plays, I have had a look on their website and can not work out where I need to add the relevant auto play code!
Here is the jquery.roundabout.js code:
// creates a default shape to be used for pathing
jQuery.extend({
roundabout_shape: {
def: 'lazySusan',
lazySusan: function(r, a, t) {
return {
x: Math.sin(r + a),
y: (Math.sin(r + 3*Math.PI/2 + a) / 8) * t,
z: (Math.cos(r + a) + 1) / 2,
scale: (Math.sin(r + Math.PI/2 + a) / 2) + 0.5
};
}
}
});
jQuery.fn.roundabout = function() {
var options = (typeof arguments[0] != 'object') ? {} : arguments[0];
// set options and fill in defaults
options = {
bearing: (typeof options.bearing == 'undefined') ? 0.0 : jQuery.roundabout_toFloat(options.bearing % 360.0),
tilt: (typeof options.tilt == 'undefined') ? 0.0 : jQuery.roundabout_toFloat(options.tilt),
minZ: (typeof options.minZ == 'undefined') ? 100 : parseInt(options.minZ, 10),
maxZ: (typeof options.maxZ == 'undefined') ? 400 : parseInt(options.maxZ, 10),
minOpacity: (typeof options.minOpacity == 'undefined') ? 0.40 : jQuery.roundabout_toFloat(options.minOpacity),
maxOpacity: (typeof options.maxOpacity == 'undefined') ? 1.00 : jQuery.roundabout_toFloat(options.maxOpacity),
minScale: (typeof options.minScale == 'undefined') ? 0.40 : jQuery.roundabout_toFloat(options.minScale),
maxScale: (typeof options.maxScale == 'undefined') ? 1.00 : jQuery.roundabout_toFloat(options.maxScale),
duration: (typeof options.duration == 'undefined') ? 600 : parseInt(options.duration, 10),
btnNext: options.btnNext || null,
btnPrev: options.btnPrev || null,
easing: options.easing || 'swing',
clickToFocus: (options.clickToFocus !== false),
focusBearing: (typeof options.focusBearing == 'undefined') ? 0.0 : jQuery.roundabout_toFloat(options.focusBearing % 360.0),
shape: options.shape || 'lazySusan',
debug: options.debug || false,
childSelector: options.childSelector || 'li',
startingChild: (typeof options.startingChild == 'undefined') ? null : parseInt(options.startingChild, 10),
reflect: (typeof options.reflect == 'undefined' || options.reflect === false) ? false : true
};
// assign things
this.each(function(i) {
var ref = jQuery(this);
var period = jQuery.roundabout_toFloat(360.0 / ref.children(options.childSelector).length);
var startingBearing = (options.startingChild === null) ? options.bearing : options.startingChild * period;
// set starting styles
ref
.addClass('roundabout-holder')
.css('padding', 0)
.css('position', 'relative')
.css('z-index', options.minZ);
// set starting options
ref.data('roundabout', {
'bearing': startingBearing,
'tilt': options.tilt,
'minZ': options.minZ,
'maxZ': options.maxZ,
'minOpacity': options.minOpacity,
'maxOpacity': options.maxOpacity,
'minScale': options.minScale,
'maxScale': options.maxScale,
'duration': options.duration,
'easing': options.easing,
'clickToFocus': options.clickToFocus,
'focusBearing': options.focusBearing,
'animating': 0,
'childInFocus': -1,
'shape': options.shape,
'period': period,
'debug': options.debug,
'childSelector': options.childSelector,
'reflect': options.reflect
});
// bind click events
if (options.clickToFocus === true) {
ref.children(options.childSelector).each(function(i) {
jQuery(this).click(function(e) {
var degrees = (options.reflect === true) ? 360.0 - (period * i) : period * i;
degrees = jQuery.roundabout_toFloat(degrees);
if (!jQuery.roundabout_isInFocus(ref, degrees)) {
e.preventDefault();
if (ref.data('roundabout').animating === 0) {
ref.roundabout_animateAngleToFocus(degrees);
}
return false;
}
});
});
}
// bind next buttons
if (options.btnNext) {
jQuery(options.btnNext).bind('click.roundabout', function(e) {
e.preventDefault();
if (ref.data('roundabout').animating === 0) {
ref.roundabout_animateToNextChild();
}
return false;
});
}
// bind previous buttons
if (options.btnPrev) {
jQuery(options.btnPrev).bind('click.roundabout', function(e) {
e.preventDefault();
if (ref.data('roundabout').animating === 0) {
ref.roundabout_animateToPreviousChild();
}
return false;
});
}
});
// start children
this.roundabout_startChildren();
// callback once ready
if (typeof arguments[1] === 'function') {
var callback = arguments[1], ref = this;
setTimeout(function() { callback(ref); }, 0);
}
return this;
};
jQuery.fn.roundabout_startChildren = function() {
this.each(function(i) {
var ref = jQuery(this);
var data = ref.data('roundabout');
var children = ref.children(data.childSelector);
children.each(function(i) {
var degrees = (data.reflect === true) ? 360.0 - (data.period * i) : data.period * i;
// apply classes and css first
jQuery(this)
.addClass('roundabout-moveable-item')
.css('position', 'absolute');
// then measure
jQuery(this).data('roundabout', {
'startWidth': jQuery(this).width(),
'startHeight': jQuery(this).height(),
'startFontSize': parseInt(jQuery(this).css('font-size'), 10),
'degrees': degrees
});
});
ref.roundabout_updateChildPositions();
});
return this;
};
jQuery.fn.roundabout_setTilt = function(newTilt) {
this.each(function(i) {
jQuery(this).data('roundabout').tilt = newTilt;
jQuery(this).roundabout_updateChildPositions();
});
if (typeof arguments[1] === 'function') {
var callback = arguments[1], ref = this;
setTimeout(function() { callback(ref); }, 0);
}
return this;
};
jQuery.fn.roundabout_setBearing = function(newBearing) {
this.each(function(i) {
jQuery(this).data('roundabout').bearing = jQuery.roundabout_toFloat(newBearing % 360, 2);
jQuery(this).roundabout_updateChildPositions();
});
if (typeof arguments[1] === 'function') {
var callback = arguments[1], ref = this;
setTimeout(function() { callback(ref); }, 0);
}
return this;
};
jQuery.fn.roundabout_adjustBearing = function(delta) {
delta = jQuery.roundabout_toFloat(delta);
if (delta !== 0) {
this.each(function(i) {
jQuery(this).data('roundabout').bearing = jQuery.roundabout_getBearing(jQuery(this)) + delta;
jQuery(this).roundabout_updateChildPositions();
});
}
if (typeof arguments[1] === 'function') {
var callback = arguments[1], ref = this;
setTimeout(function() { callback(ref); }, 0);
}
return this;
};
jQuery.fn.roundabout_adjustTilt = function(delta) {
delta = jQuery.roundabout_toFloat(delta);
if (delta !== 0) {
this.each(function(i) {
jQuery(this).data('roundabout').tilt = jQuery.roundabout_toFloat(jQuery(this).roundabout_get('tilt') + delta);
jQuery(this).roundabout_updateChildPositions();
});
}
if (typeof arguments[1] === 'function') {
var callback = arguments[1], ref = this;
setTimeout(function() { callback(ref); }, 0);
}
return this;
};
jQuery.fn.roundabout_animateToBearing = function(bearing) {
bearing = jQuery.roundabout_toFloat(bearing);
var currentTime = new Date();
var duration = (typeof arguments[1] == 'undefined') ? null : arguments[1];
var easingType = (typeof arguments[2] == 'undefined') ? null : arguments[2];
var passedData = (typeof arguments[3] !== 'object') ? null : arguments[3];
this.each(function(i) {
var ref = jQuery(this), data = ref.data('roundabout'), timer, easingFn, newBearing;
var thisDuration = (duration === null) ? data.duration : duration;
var thisEasingType = (easingType !== null) ? easingType : data.easing || 'swing';
if (passedData === null) {
passedData = {
timerStart: currentTime,
start: jQuery.roundabout_getBearing(ref),
totalTime: thisDuration
};
}
timer = currentTime - passedData.timerStart;
if (timer < thisDuration) {
data.animating = 1;
if (typeof jQuery.easing.def == 'string') {
easingFn = jQuery.easing[thisEasingType] || jQuery.easing[jQuery.easing.def];
newBearing = easingFn(null, timer, passedData.start, bearing - passedData.start, passedData.totalTime);
} else {
newBearing = jQuery.easing[thisEasingType]((timer / passedData.totalTime), timer, passedData.start, bearing - passedData.start, passedData.totalTime);
}
ref.roundabout_setBearing(newBearing, function() { ref.roundabout_animateToBearing(bearing, thisDuration, thisEasingType, passedData); });
} else {
bearing = (bearing < 0) ? bearing + 360 : bearing % 360;
data.animating = 0;
ref.roundabout_setBearing(bearing);
}
});
return this;
};
jQuery.fn.roundabout_animateToDelta = function(delta) {
var duration = arguments[1], easing = arguments[2];
this.each(function(i) {
delta = jQuery.roundabout_getBearing(jQuery(this)) + jQuery.roundabout_toFloat(delta);
jQuery(this).roundabout_animateToBearing(delta, duration, easing);
});
return this;
};
jQuery.fn.roundabout_animateToChild = function(childPos) {
var duration = arguments[1], easing = arguments[2];
this.each(function(i) {
var ref = jQuery(this), data = ref.data('roundabout');
if (data.childInFocus !== childPos && data.animating === 0) {
var child = jQuery(ref.children(data.childSelector)[childPos]);
ref.roundabout_animateAngleToFocus(child.data('roundabout').degrees, duration, easing);
}
});
return this;
};
jQuery.fn.roundabout_animateToNearbyChild = function(passedArgs, which) {
var duration = passedArgs[0], easing = passedArgs[1];
this.each(function(i) {
var data = jQuery(this).data('roundabout');
var bearing = jQuery.roundabout_toFloat(360.0 - jQuery.roundabout_getBearing(jQuery(this)));
var period = data.period, j = 0, range;
var reflect = data.reflect;
var length = jQuery(this).children(data.childSelector).length;
bearing = (reflect === true) ? bearing % 360.0 : bearing;
if (data.animating === 0) {
// if we're not reflecting and we're moving to next or
// we are reflecting and we're moving previous
if ((reflect === false && which === 'next') || (reflect === true && which !== 'next')) {
bearing = (bearing === 0) ? 360 : bearing;
// counterclockwise
while (true && j < length) {
range = { lower: jQuery.roundabout_toFloat(period * j), upper: jQuery.roundabout_toFloat(period * (j + 1)) };
range.upper = (j == length - 1) ? 360.0 : range.upper; // adjust for javascript being bad at floats
if (bearing <= range.upper && bearing > range.lower) {
jQuery(this).roundabout_animateToDelta(bearing - range.lower, duration, easing);
break;
}
j++;
}
} else {
// clockwise
while (true) {
range = { lower: jQuery.roundabout_toFloat(period * j), upper: jQuery.roundabout_toFloat(period * (j + 1)) };
range.upper = (j == length - 1) ? 360.0 : range.upper; // adjust for javascript being bad at floats
if (bearing >= range.lower && bearing < range.upper) {
jQuery(this).roundabout_animateToDelta(bearing - range.upper, duration, easing);
break;
}
j++;
}
}
}
});
return this;
};
jQuery.fn.roundabout_animateToNextChild = function() {
return this.roundabout_animateToNearbyChild(arguments, 'next');
};
jQuery.fn.roundabout_animateToPreviousChild = function() {
return this.roundabout_animateToNearbyChild(arguments, 'previous');
};
// moves a given angle to the focus by the shortest means possible
jQuery.fn.roundabout_animateAngleToFocus = function(target) {
var duration = arguments[1], easing = arguments[2];
this.each(function(i) {
var delta = jQuery.roundabout_getBearing(jQuery(this)) - target;
delta = (Math.abs(360.0 - delta) < Math.abs(0.0 - delta)) ? 360.0 - delta : 0.0 - delta;
delta = (delta > 180) ? -(360.0 - delta) : delta;
if (delta !== 0) {
jQuery(this).roundabout_animateToDelta(delta, duration, easing);
}
});
return this;
};
jQuery.fn.roundabout_updateChildPositions = function() {
this.each(function(i) {
var ref = jQuery(this), data = ref.data('roundabout');
var inFocus = -1;
var info = {
bearing: jQuery.roundabout_getBearing(ref),
tilt: data.tilt,
stage: { width: Math.floor(ref.width() * 0.9), height: Math.floor(ref.height() * 0.9) },
animating: data.animating,
inFocus: data.childInFocus,
focusBearingRad: jQuery.roundabout_degToRad(data.focusBearing),
shape: jQuery.roundabout_shape[data.shape] || jQuery.roundabout_shape[jQuery.roundabout_shape.def]
};
info.midStage = { width: info.stage.width / 2, height: info.stage.height / 2 };
info.nudge = { width: info.midStage.width + info.stage.width * 0.05, height: info.midStage.height + info.stage.height * 0.05 };
info.zValues = { min: data.minZ, max: data.maxZ, diff: data.maxZ - data.minZ };
info.opacity = { min: data.minOpacity, max: data.maxOpacity, diff: data.maxOpacity - data.minOpacity };
info.scale = { min: data.minScale, max: data.maxScale, diff: data.maxScale - data.minScale };
// update child positions
ref.children(data.childSelector).each(function(i) {
if (jQuery.roundabout_updateChildPosition(jQuery(this), ref, info, i) && info.animating === 0) {
inFocus = i;
jQuery(this).addClass('roundabout-in-focus');
} else {
jQuery(this).removeClass('roundabout-in-focus');
}
});
// update status of who is in focus
if (inFocus !== info.inFocus) {
jQuery.roundabout_triggerEvent(ref, info.inFocus, 'blur');
if (inFocus !== -1) {
jQuery.roundabout_triggerEvent(ref, inFocus, 'focus');
}
data.childInFocus = inFocus;
}
});
return this;
};
//----------------
jQuery.roundabout_getBearing = function(el) {
return jQuery.roundabout_toFloat(el.data('roundabout').bearing) % 360;
};
jQuery.roundabout_degToRad = function(degrees) {
return (degrees % 360.0) * Math.PI / 180.0;
};
jQuery.roundabout_isInFocus = function(el, target) {
return (jQuery.roundabout_getBearing(el) % 360 === (target % 360));
};
jQuery.roundabout_triggerEvent = function(el, child, eventType) {
return (child < 0) ? this : jQuery(el.children(el.data('roundabout').childSelector)[child]).trigger(eventType);
};
jQuery.roundabout_toFloat = function(number) {
number = Math.round(parseFloat(number) * 1000) / 1000;
return parseFloat(number.toFixed(2));
};
jQuery.roundabout_updateChildPosition = function(child, container, info, childPos) {
var ref = jQuery(child), data = ref.data('roundabout'), out = [];
var rad = jQuery.roundabout_degToRad((360.0 - ref.data('roundabout').degrees) + info.bearing);
// adjust radians to be between 0 and Math.PI * 2
while (rad < 0) {
rad = rad + Math.PI * 2;
}
while (rad > Math.PI * 2) {
rad = rad - Math.PI * 2;
}
var factors = info.shape(rad, info.focusBearingRad, info.tilt); // obj with x, y, z, and scale values
// correct
factors.scale = (factors.scale > 1) ? 1 : factors.scale;
factors.adjustedScale = (info.scale.min + (info.scale.diff * factors.scale)).toFixed(4);
factors.width = (factors.adjustedScale * data.startWidth).toFixed(4);
factors.height = (factors.adjustedScale * data.startHeight).toFixed(4);
// alter item
ref
.css('left', ((factors.x * info.midStage.width + info.nudge.width) - factors.width / 2.0).toFixed(1) + 'px')
.css('top', ((factors.y * info.midStage.height + info.nudge.height) - factors.height / 2.0).toFixed(1) + 'px')
.css('width', factors.width + 'px')
.css('height', factors.height + 'px')
.css('opacity', (info.opacity.min + (info.opacity.diff * factors.scale)).toFixed(2))
.css('z-index', Math.round(info.zValues.min + (info.zValues.diff * factors.z)))
.css('font-size', (factors.adjustedScale * data.startFontSize).toFixed(2) + 'px')
.attr('current-scale', factors.adjustedScale);
if (container.data('roundabout').debug === true) {
out.push('<div style="font-weight: normal; font-size: 10px; padding: 2px; width: ' + ref.css('width') + '; background-color: #ffc;">');
out.push('<strong style="font-size: 12px; white-space: nowrap;">Child ' + childPos + '</strong><br />');
out.push('<strong>left:</strong> ' + ref.css('left') + '<br /><strong>top:</strong> ' + ref.css('top') + '<br />');
out.push('<strong>width:</strong> ' + ref.css('width') + '<br /><strong>opacity:</strong> ' + ref.css('opacity') + '<br />');
out.push('<strong>z-index:</strong> ' + ref.css('z-index') + '<br /><strong>font-size:</strong> ' + ref.css('font-size') + '<br />');
out.push('<strong>scale:</strong> ' + ref.attr('current-scale'));
out.push('</div>');
ref.html(out.join(''));
}
return jQuery.roundabout_isInFocus(container, ref.data('roundabout').degrees);
};
Many thanks in advance for any help and advice.
Phil
The source you posted doesn't seem to be the latest version of Roundabout.
I just tried with the latest version, and it works perfectly:
$(document).ready(function() {
$('ul').roundabout({
autoplay: true,
autoplayDuration: 1000,
autoplayPauseOnHover: true
});
});
See http://jsfiddle.net/SfAuF/ for an example.
Download the latest version from GitHub.

Categories

Resources