Setting the body elements left margin using JavaScript does not work, it doesn't move
I don't know why this doesn't work. If I set the left margin using CSS, it works, but not when I do it in JavaScript, why?
<html>
<head>
<style type="text/css">
<!--
body { margin-left: 0px; } /* set margin to anything so I can change it in JS*/
-->
</head>
<body>
<div id="test" style="background-color: blue;"> blah </div>
<script type="text/javascript">
<!--
var APP_WIDTH = 555;
var scrWidth = 760; //getScreenSize()["width"];
var xOffset = Math.abs( Math.floor( (scrWidth/2)-(APP_WIDTH/2) ) );
document.getElementsByTagName("body")[0].style.margin.left = xOffset + "px"; // doesn't move the div inside body?
alert( xOffset + "px" );
-->
</script>
</body>
</html>
To change the margin of a HTML Element using JavaScript, get reference to this HTML Element, and assign required margin value to the element. style. margin property. In the following example, we will change the margin of HTML Element with id "myElement" to "20px" , in JavaScript, using element.
margin: 10px 5px 15px 20px; top margin is 10px. right margin is 5px. bottom margin is 15px. left margin is 20px.
document.getElementsByTagName("body")[0].style.margin.left
should be:
document.getElementsByTagName("body")[0].style.marginLeft
(notice the final property).
Use:
document.body.style.margin = "0px 0px 0px " + xOffset + "px";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With