Reputation: 12363
I am try position a div using absolute positioning and it works fine in Safari and Firefox but fails in IE and I can't figure out why. The code is this:
var tempX=123;
var tempY=456;
var commentnum=3;
var bodyelement = document.getElementsByTagName('body')[0];
var newdiv = document.createElement('div');
newdiv.setAttribute('id', 'comment_text'+commentnum);
newdiv.setAttribute('style', 'text-align:center;z-index:10001;left:'+(tempX-23)+'px;top:'+(tempY-80)+'px;position:absolute;');
newdiv.innerHTML = commenthtml;
bodyelement.appendChild(newdiv);
The script is suppose to generate a div where the user clicks the mouse. But in IE it places the div to the left side and then stacks them on top of each other. Can anyone give me an idea why this is not working?
Upvotes: 0
Views: 1669
Reputation: 7597
Could your answer be as simple as position:relative
assigned to body
?
The way your divs are acting seems like the second is being positioned differently due to the flow of the parent container relative to its children.
Upvotes: 0
Reputation: 322452
According to quirksmode, setAttribute
can not be used to set the style
attribute in IE.
Using setAttribute, you should be able to set any attribute on an element. It appears that in IE, trying to set the style attribute does not work.
Instead you may need to set the style properties individually:
newdiv.style.textAlign = 'center';
newdiv.style.zIndex = 10001;
newdiv.style.left = (tempX-23) + 'px';
newdiv.style.top = (tempY-80) + 'px';
newdiv.style.position = 'absolute';
EDIT:
It appears as though IE
has a cssText
property. I'm not sure about browser support, but perhaps you could test for it.
if( 'cssText' in newdiv.style ) {
newdiv.style.cssText = 'text-align:center;z-index:10001;left:'+(tempX-23)+'px;top:'+(tempY-80)+'px;position:absolute;';
} else {
newdiv.setAttribute('style', 'text-align:center;z-index:10001;left:'+(tempX-23)+'px;top:'+(tempY-80)+'px;position:absolute;');
}
Tested cssText
in Chrome 10 and Firefox 3.6, and it works.
EDIT2:
It appears as though there's wide support for that property on elem.style
, so you may just want to use it instead of setAttribute()
.
newdiv.style.cssText = 'text-align:center;z-index:10001;left:'+(tempX-23)+'px;top:'+(tempY-80)+'px;position:absolute;';
Upvotes: 6
Reputation: 66399
Try assigning the style directly, not via setAttribute
:
newdiv.style.position = "absolute";
newdiv.style.left = (tempX-23) + "px";
newdiv.style.top = (tempY-80) + "px";
Upvotes: 3