Skip to content

Instantly share code, notes, and snippets.

@Rycochet
Created September 16, 2014 09:37
Show Gist options
  • Save Rycochet/cb9d6a101a29c85b3331 to your computer and use it in GitHub Desktop.
Save Rycochet/cb9d6a101a29c85b3331 to your computer and use it in GitHub Desktop.
Convert CSS values to a usable number, parses calc() for a single depth only
/**
* Convert a css number type string into pixel units
* @param {jQuerySelector} $el
* @param {String} value
* @param {?Boolean} horiz
* @returns {Number}
*/
function convertCSS($el, value, horiz) {
var val = parseFloat(value);
// console.log("convertCSS", value, value.replace(/[^a-z%]/g, ""), horiz)
switch (value.replace(/[^a-z%]/g, "").substr(0, 4)) {
case "none":
val = 0;
break;
case "calc":
var operand, num,
sum = value.replace(/^calc\(|\)$/g, "").split(" ");
val = convertCSS($el, sum.shift(), horiz);
while (sum.length) {
if (operand) {
num = convertCSS($el, sum.shift(), horiz);
if (operand === "+") {
val += num;
} else if (operand === "-") {
val -= num;
} else if (operand === "*") {
val *= num;
} else if (operand === "/") {
val /= num;
}
operand = "";
} else {
operand = sum.shift();
}
}
break;
case "em":
val *= parseFloat($el.css("fontSize"));
break;
case "percent":
val *= $el.offsetParent()[horiz ? "width" : "height"]() / 100;
break
case "rem":
val *= parseFloat($("html").css("fontSize"));
break;
case "vh":
val *= window.innerHeight / 100;
break;
case "vw":
val *= window.innerWidth / 100;
break;
case "vmin":
val *= Math.min(window.innerWidth, window.innerHeight) / 100;
break;
case "vmax":
val *= Math.max(window.innerWidth, window.innerHeight) / 100;
break;
case "px":
case "":
break;
default:
console.warn("convertCSS: Unknown conversion type!! (" + value + ")");
}
// console.log("=", val);
return value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment