December 27, 2000 - String-Based Physical Measurements
![]() |
December 27, 2000 String-Based Physical Measurements Tips: December 2000
Yehuda Shiran, Ph.D.
|
STYLE object's properties (such as left and top) denote physical measurements, they are strings in JavaScript. Fail to do so, and you will get into long debugging sessions. When you need the pure numeric value of either left or top, use the parseInt() method. This method parses a string from left to right, converting the string to an integer. Parsing stops when there is no way to make an integer out of the string. For example, parseInt("50px") is 50. The following code segment adds 50 pixels to the button's left property, every time the user clicks the button:
<FORM>
<INPUT ID="counter1" STYLE="position:relative; left:0px" TYPE="button"
VALUE="Move Button" onclick="handleClick()">
</FORM>
<SCRIPT LANGUAGE="JavaScript">
<!--
var obj = document.getElementById('counter1');
var xlocation = parseInt(obj.style.left);
alert(xlocation);
function handleClick() {
xlocation += 50;
document.getElementById('counter1').style.left = xlocation + "px";
}
// -->
</SCRIPT>Try it repetitively:
Notice that numeric operations (incrementing by 50) are done with the integer-typed
xlocation. We set the left value by assembling xlocation and "px".



