I was working on something the other day and needed a quick snippet of JavaScript to convert values to pixels from any string. Below is a quick function:
function px(val) {
return parseInt(val)+"px";
}
}
To use it, just wrap your string with the function and it should convert it to pixels for you:
var oldValue = '65';
var newValue = px(oldValue);
Let me know how this works for you and if you make any modifications to improve it. Thanks!
Hi Chris,
I am just wondering why you need this function at all. As you can see by declaring "var" before a variable in javascript it does not really care if a string or integer is held in it unless you are doing validation or variable specific tasks.
So .. First of all, you create your variable "oldValue" (which could be anything at all as input to your function) that should be an integer number to represent a pixel value in HTML - by adding "px".
Why not simply state;
var oldvalue = '65'; (this has been created as a string - but javascript does not care)
var newValue = oldValue + "px"; (newValue is now equal to "65px")
document.write(newValue);
Another thing is that by using the parseInt function (this function is used to parse an integer and return a string), in essence you are passing a string into a function that converts this to an integer, parses it and once again returns a string. This function is better suited to parsing strings that might contain both an integer and a string "tail" or in converting different numerical systems such as decimal to octal. You can see an example here : http://www.w3schools.com/jsref/jsref_parseInt.asp
The only purpose I could see in using this would be for validation but then there is nothing done inside the function px() to handle any errors.
Its amazing how such a small piece of code can cause such a discussion, please let me know what it is that I may have missed.
Darren
- spam
- offensive
- disagree
- off topic
Like@Darren I agree with you, I don't think this function makes sense anymore. It originally was a larger function that checked to see if 'px' was already a part of the string, and if yes, it should return the string untouched. The validation of the string is what I need.
Here's the process I was looking for:
Check if passed variable is a number
if yes return number+px
if no strip alpha characters from beginning or end of number
return number+px
- spam
- offensive
- disagree
- off topic
Like