spacer
Yehuda Shiran December 14, 2000
Manipulating Element Coordinates
Tips: December 2000

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
Microsoft Shows Off Silverlight 4, IE9 Plans
Metasploit Expands Vulnerability Test Framework
HyperCard Reborn?

The browser-independent W3C Standard's way to set and get an element position is via the style object's left and top properties. Although these properties denote physical measurements, they are strings. It's important to remember it, or else you'll 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's 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 xlocation = parseInt(document.getElementById('counter1').style.left);
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".


People who read this tip also read these tips:

Look for similar tips by subject:

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Rolling Out Your Own HTML Application Version Control · HTML 5: Client-side Storage · Working with Ajax Server Extensions
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Wi-Fi Product Watch, November 2009 · Chip Market Recovering From '08 Collapse · Low-Cost Tools to Kickstart Your New Business