16 October, 2009
5 Comments
0 categories
If you want to alter an elements CSS width or height, you must first convert this value to an integer, because the CSS value can have units like px, cm etc.
To convert this value to an integer in javascript, use:
// Convert a css px value to int. function ConvertCssPxToInt(cssPxValueText) { // Set valid characters for numeric number. var validChars = "0123456789."; // If conversion fails return 0. var convertedValue = 0; // Loop all characters of for (i = 0; i < cssPxValueText.length; i++) { // Stop search for valid numeric characters, when a none numeric number is found. if (validChars.indexOf(cssPxValueText.charAt(i)) == -1) { // Start conversion if at least one character is valid. if (i > 0) { // Convert validnumbers to int and return result. convertedValue = parseInt(cssPxValueText.substring(0, i)); return convertedValue; } } } return convertedValue; }
Tags: Javascript
Simple parseInt(cssPxValueText) function build in javascript will do. Funny functionality of that function anyway :>.
@Adam…that functionality breaks in IE6 :/
function ConvertCssPxToInt(cssPxValueText){
return parseInt(cssPxValueText.substring(cssPxValueText.length – 2, cssPxValueText.length));
}
parseInt
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
example
>> parseInt(’20px’, 10);
20
Can any one please tell me how I convert pixel into interger and vies versa?