Categories:
Partners

Defining dynamic properties inside your script

You can also define dynamic properties via scripting, thanks to the below methods of IE5+:

Method Description
setExpression() Sets a dynamic expression on the given element:
setExpression(PropertyName, theExpression, optionalLanguage).
getExpression() Returns the current expression set on the given element:
getExpression(PropertyName).
removeExpression() Removes the current expression on the given element, or rather, the dependency between your HTML property value and the dynamic expression's:
removeExpression(PropertyName).
recalc() Forcibly re-evaluates the value of the dynamic expression. When optional parameter is set to true, it re-evaluates all dynamic expressions on the page, rather than just the ones it thinks are affected by the last user action (such as resizing the window):
document.recalc(optionalBoolean).

Lets take one of the previous examples of positioning an image in the center of the browser, but this time, do so entirely within a script:

<img id="cat" src="../test.gif" style="width: 120px; height: 150px; position: absolute;" />

<script type="text/javascript">
var targetEl=document.getElementById("cat")
var docElement=(document.compatMode=='CSS1Compat')? document.documentElement: document.body


if (targetEl.setExpression){
targetEl.style.setExpression("left", "(docElement.clientWidth-120)/2+'px'")
targetEl.style.setExpression("top", "(docElement.clientHeight-150)/2+'px'")
}

</script>

Notice how in the "if" statement, I've tested for the existence of setExpression() on element "targetEl" itself to detect whether the browser supports this method before proceeding, while for the statements that follows that actually utilize the method, I've invoked it on the style object of the element. The point I'm trying to make with that is that setExpression() exists on both levels of the element's hierarchy, as dynamic properties is applicable not to just to the "style" property, but other properties of elements as well.

And with that we come to the end of the tutorial. Hope you've found Dynamic Expressions as useful as it is interesting!