|
Working
With Elements
Now
that you have a consistent way to reference <DIV>
elements, I'll show
you the different ways to manipulate them via JavaScript. You access
all element style attributes through a single collection, called
style in both NS6
and IE, so now you finally have a consistent cross-browser approach
to manipulating elements.
Before
we go on, there's an important thing you must know about NS6. The
reason I declared the sample <DIV>
tag's style values using the style attribute rather than using a
stylesheet is because NS6 has an unfortunate behavior in which style
values declared in a stylesheet are not populated into an element's
style collection. Whether this is a bug or correct behavior in light
of cascading rules is currently being debated. In any case, to write
DHTML that consistently works in both NS6 and IE5 you must declare
your style information in the style
attribute of your <DIV>
tags, regardless of which browser you are using.
Hiding
and Showing
Before
you can manipulate an element, you must obtain a reference to it.
Here's an example that uses the sampleDiv layer shown earlier:
var myElement
= document.getElementById("sampleDiv");
Set
the visibility property
of a layer to hidden or visible as necessary (the old Netscape 4.x
values hide and show will not work in NS6):
myElement.style.visibility
= "hidden"; // hides the layer
myElement.style.visibility = "visible"; // reveals it
again
Example:
hiding and showing
Finding
Position
To
retrieve the x and y coordinates of a layer element, access it's
left and top
style properties:
var myElement
= document.getElementById("sampleDiv");
var l = myElement.style.left;
var t = myElement.style.top;
alert("Position is: left " + l + ", top " +
t);
The
above example would display: "Position is: left 300px, top
200px"
Note
that in each case, the returned value is a string, not a number.
That's because the "px" suffix specifies the unit of measurement
as pixels. If you want to animate the layer you need to convert
this string into an integer, as you'll see in the next example.
|
IE
compatibility note:
IE5x
browsers still support the pixelLeft and pixelTop style properties,
which are represented as numbers. However, because both IE
and NS6 support style.left and style.top, there's no reason
to use them.
|
|