Skip to content

Instantly share code, notes, and snippets.

@megawac
Last active December 22, 2015 20:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save megawac/6525074 to your computer and use it in GitHub Desktop.
Save megawac/6525074 to your computer and use it in GitHub Desktop.
Mootools css calc polyfill. Only for relatively simple cases. Usage: util.calc($$('div')[8], 'width', '70% - 40px'); This will yield a cross browser calc. It uses native if it should be supported. Only supporting a few units for now.
//http://caniuse.com/#feat=calc
//union bool str (-webkit-calc, -moz-calc, calc)
//alternatively see last version where i did a version check based on can i use
document.addEvent("domready", function() {//based off https://gist.github.com/Rob-ot/3399053
Browser.Features.calc = false;//union bool str (-webkit-calc, -moz-calc, calc)
["","-webkit-","-moz-","-o-"].some(function(prefix) {
var $el = new Element('div', {
styles: {
width: prefix + "calc(5px)"
}
});
if ($el.style.length > 0) return Browser.Features.calc = prefix + "calc";
});
});
util.percentToPixel = function(data, par) {
par = par || $(document.body);
var size = par.getSize();
return {
x: size.x * (data.x * .01),
y: size.y * (data.y * .01)
};
};
//https://gist.github.com/megawac/6525074
//http://www.w3schools.com/cssref/css_units.asp
util.calc = function($ele, style, val) {
// val = val.replace(/(\(|\))/g, "");
//simple css calc function polyfill
//polyfill expects surrounded by brackets <val><unit> <operator> <val><unit> => "33% - 20px + 1em"
//does not support things like "50%/3 - 5px"
if (Browser.Features.calc) {
$ele.setStyle(style, Browser.Features.calc + "(" + val + ")");
} else {
var old = $ele.retrieve("calc");
if (old) {
window.removeEvent("resize", old);
}
var split = val.split(" ");
var op = split.splice(1, 1);
var resize = function() {
var expr = val.replace(/(\d+)(\S+)/g, function(match, size, unit) {
size = size.toFloat();
switch (unit) { //unit
case "%":
var data = {};
var dir = style.contains("width") ? "x" : "y";
data[dir] = size;
return util.percentToPixel(data, $ele.getParent())[dir].round(3);
case "em":
var fsize = $ele.getStyle("font-size").toFloat();
return fsize * size;
// case "px":
default:
return size;
}
});
var size = eval(expr); //safe usage - evals '500-20+12' for example
$ele.setStyle(style, size);
return resize;
};
window.addEvent("resize", resize);
$ele.store("calc", resize);
return resize();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment