Reputation: 433
I am trying to reposition a div on the page depending on a certain condition.
if (somecondition)
document.getElementById("Div1").setAttribute("style", "position: absolute; left:297px; top:882px; height: 30px; width: 181px; margin-top: 0px;");
It is not repositioning the div in the html below:
<div id="Div1" style="top:366px; left:134px; position:absolute; height: 30px; width: 175px;">
Other code in the if fires.
Can anyone help? Browser: IE8
Upvotes: 3
Views: 7151
Reputation: 21
Make two style classes and add two different positions to the classes. Then change the DIVs class if javascript condition is satisfied. E.g:
if(someCondition) {
document.getElementById('Div1').setAttribute('class', 'style2');
} else {
document.getElementById('Div1').setAttribute('class', 'style1');
}
CSS Styles
.style1 {
top:366px;
left:134px;
position:absolute;
height: 30px;
width: 175px;
}
.style2 {
position: absolute;
left:297px;
top:882px;
height: 30px;
width: 181px;
margin-top: 0px;
HTML
<div id="Div1" class="style1"></div>
Upvotes: 2
Reputation: 6043
Its working perfectly all right, check out the demo here.
HTML:
<div id="Div1" style="top:366px; left:134px; position:absolute; height: 30px; width: 175px;">
hello world
</div>
Javascript:
document.getElementById("Div1").setAttribute("style", "position: absolute; left:297px; top:82px; height: 30px; width: 181px; margin-top: 0px;");
Upvotes: 2
Reputation: 4368
To use the CSS as a single string, you should set the Element.style.cssText
property:
var element = document.getElementById("Div1");
element.style.cssText = "position: absolute; left:297px; top:882px; height: 30px; " +
"width: 181px; margin-top: 0px;";
Upvotes: 2
Reputation: 2156
Didn't you put the javascript code in the document.ready(function(){});?
Upvotes: 0
Reputation: 5131
You only need to do
document.getElementById("Div1").style.<some css property> = <some value>; // like
document.getElementById("Div1").style.left = "297px";
document.getElementById("Div1").style.top = "882px";
(of course you should cache the getELementById)
Upvotes: 3
Reputation: 5563
try like
document.getElementById("Div1").style.left = "297px";
document.getElementById("Div1").style.top = "882px";
Upvotes: 1
Reputation: 35963
Using setAttribute is unreliable if you want the change to be reflected in the document. Use Element.style instead:
var el = document.getElementById('Div1');
el.style.position = 'absolute';
el.style.left = '397px';
el.style.top = '882px';
el.style.height = '30px';
el.style.width = '181px';
el.style.marginTop = '0px';
Upvotes: 7