Sunday, 18 September 2011

Cross-Browse Dynamic HTML Moving an Element


Moving an Element

Generally there is no compatibility problems when assigning a new location for the element(CSS Element).  You simply assign new left and top values:
myelement.left = 100
myelement.top = 50
if, myelement is a pointer variable defined something like this:
function init() {
                     if (ns4) myelement = document.myelementDiv
                     if (ie4) myelement = myelementDiv.style
}
Problem
How ever there is a problem when capturing the current location of the element. This is due to the fact that IE stores its location with “px” at the end of the value. To get rid of this “px” you have to parse the value into an integer. So instead of writing
myelement.left
You have to write
parseInt(myelement.left)
For example, if you wanted to pop up an alert of the current left and top location you'd write:
alert(parseInt(myelement.left) + ", " + parseInt(myelement.top))

A Better Way (The Cross Browser Method

Instead of always having to write parseInt() before all your variables, a better way is to add more properties to your pointer variables or object. To make these new properties just assign them..
myelement.xpos = parseInt(myelement.left)
myelement.ypos = parseInt(myelement.top)
Usage
When you want to change the location of the element, you FIRST have to change the values of xpos and ypos. THEN you set the left and top values equal to xpos and ypos respectively. For example:
function move() {
                     myelement.xpos = 200
                     myelement.ypos = -40
                     myelement.left = myelement.xpos
                     myelement.top = myelement.ypos
}

No comments:

Post a Comment

Please Give Your Valuable Comments on this Topic

Archives