CanGrow/playground/html/material-gauge-gh-pages/material-gauge.js

84 lines
2.5 KiB
JavaScript

// #### Gauge
// The Gauge object encapsulates the behavior
// of simple gauge. Most of the implementation
// is in the CSS rules, but we do have a bit
// of JavaScript to set or read the gauge value
function Gauge(el) {
// ##### Private Properties and Attributes
var element, // Containing element for the info component
data, // `.gauge__data` element
needle, // `.gauge__needle` element
value = 0.0, // Current gauge value from 0 to 1
prop, // Style for transform
valueLabel; // `.gauge__label--spacer` element
// ##### Private Methods and Functions
var setElement = function(el) {
// Keep a reference to the various elements and sub-elements
element = el;
data = element.querySelector('.gauge__data');
needle = element.querySelector('.gauge__needle');
valueLabel = element.querySelector('.gauge__label--spacer');
//valueLabel = element.getElementsByTagName('span'); //valueLabel = element.querySelector('span.gauge__label--spacer');
};
var setValue = function(x, max, unit) {
percentage = x * 100 / max;
value = percentage / 100;
var turns = -0.5 + (value * 0.5);
data.style[prop] = 'rotate(' + turns + 'turn)';
needle.style[prop] = 'rotate(' + turns + 'turn)';
valueLabel.textContent = x + unit;
/*
for (var i = 0; i < valueLabel.children.length; i++) {
window.alert(valueLabel.children[i].className);
if (valueLabel.children[i].className == 'gauge__label--spacer') {
window.alert(valueLabel.children[i]);
valueLabel.children[i].textContent = x + unit;
break;
}
}
*/
};
// ##### Object to be Returned
function exports() { };
// ##### Public API Methods
exports.element = function(el) {
if (!arguments.length) { return element; }
setElement(el);
return this;
};
exports.value = function(x, max=100, unit='%') {
if (!arguments.length) { return value; }
setValue(x, max, unit);
return this;
};
// ##### Initialization
var body = document.getElementsByTagName('body')[0];
['webkitTransform', 'mozTransform', 'msTransform', 'oTransform', 'transform'].
forEach(function(p) {
if (typeof body.style[p] !== 'undefined') { prop = p; }
}
);
if (arguments.length) {
setElement(el);
}
return exports;
};