Question: How do I create a new absolutely-positioned DIV layer from JavaScript?
Answer: Note that you can create layers without JavaScript, by using DIV HTML elements with absolute positioning. However, you can also create layers programmatically with JavaScript! Here's an example:
The above example has been created using this code:
<form>
<input type=button value="Create layer"
onClick="makeLayer('LYR1',200,10,100,100,'red',1,1)">
<input type=button value="Delete layer"
onClick="deleteLayer('LYR1')">
</form>
To create a new layer, this code calls the function
makeLayer:
makeLayer(ID,left,top,width,height,color,visible,zIndex)And here's the JavaScript source code of this function:
function makeLayer(id,L,T,W,H,bgColor,visible,zIndex) {
if (document.getElementById) {
if (document.getElementById(id)) {
alert ('Layer with this ID already exists!')
return
}
var ST= 'position:absolute'
+'; left:'+L
+'; top:'+T
+'; width:'+W
+'; height:'+H
+'; clip:rect(0,'+W+','+H+',0)'
+'; visibility:'+(null==visible || 1==visible ? 'visible':'hidden')
+(null==zIndex ? '' : '; z-index:'+zIndex)
+(null==bgColor ? '' : '; background-color:'+bgColor)
var LR= '<DIV id='+id+' style="'+ST+'"></DIV>'
if (document.body) {
if (document.body.insertAdjacentHTML) document.body.insertAdjacentHTML("BeforeEnd",LR);
else if (document.createElement && document.body.appendChild) {
var newNode = document.createElement('div');
newNode.setAttribute('id',id);
newNode.setAttribute('style',ST);
document.body.appendChild(newNode);
}
}
}
}
Copyright © 1999-2009, JavaScripter.net.