[Javascript] Re: Javascript digest, Vol 1 #181 - 13 msgs

Lewis Shadoff lshadoff at brazosport.cc.tx.us
Tue Jul 3 09:01:28 CDT 2001


At 09:46 PM 7/2/01, javascript-request at LaTech.edu wrote:

>does anyone know a way to return the coordinates of a point on a text input
>box?  Say a corner?

In IE you can get the top and left positions of the upper left of an 
element using the offsetTop and offsetLeft properties.  It requires that 
the element be positioned in a style sheet.

So... Create a style where all inputs are positioned relative (this leaves 
them in their normal position, but allows determining their position 
properties):

INPUT {
         position : relative;
}

Every input whose position you want to determine must have an ID:

[input type ="text" ID="box1"]  (I'm using [ and ] so that HTML-rendering 
email programs won't interpret this as a tag)

Create a JavaScript function that gets the position.

function getPos(ID) {
// Store the element name in bName
         var bName = ID;
// Store the x-position of the upper left corner in x
         x = document.all(bName).offsetLeft;
// Store the y-position of the upper left corner in y
         y = document.all(bName).offsetTop;
// Display the x and y positions  (remove the // on the next line to do this)
// alert("x = " + x + "\ny = " + y);
}

Call the function with a body onLoad:

[body onLoad="getPos("box1")]

If you want to make it Netscape compatible you must, instead, enclose the 
INPUT in a DIV (to create a Netscape layer) with an ID.  Then declare the 
DIV as positioned relative in a style declaration. (It's probably best to 
assign a CLASS to the DIV so you can differentiate it from normal 
DIVs.)  Give each DIV enclosing an input an ID.

DIV.inp {
         position : relative;
}

[div class="inp" id="box1"][input type=text ...][/div]

The JavaScript is now:

// Layers recognized?
var ns = (document.layers) ? true:false;
// Yes, set ns to true
// No, set ns to false

function getPos(ID) {
// Store the element name in bName
         var bName = ID;
// Check if layers recognized
         if (ns) {
// Yes, use the Netscape code
         x = document.layers[bName].pageX;
         y = document.layers[bName].pageY;
         }
         else {
// No use the IE code
         x = document.all(bName).offsetLeft;
         y = document.all(bName).offsetTop;
         }
// Dispolay the x and y values
// alert("x = " + x + "\ny = " + y);
}

If the div/input is contained within another layer, then the NS4 code 
should be:

         x = document.layers[containinglayername].document.layers[bName].pageX;
         y = document.layers[containinglayername].document.layers[bName].pageY;

If the div/layer is in a table then all bets are off!

This is not Opera (does not implement CSS2, yet) and NS6 (requires 
ECMAScript) compatible.

Lew

Lewis A. Shadoff, PhD
Brazosport College
Lake Jackson, TX





More information about the Javascript mailing list