Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set body left margin using Javascript

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>
like image 823
Mack Avatar asked Jun 20 '11 00:06

Mack


People also ask

How do I set margins in JavaScript?

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.

What does margin 10px 5px 15px 20px mean?

margin: 10px 5px 15px 20px; top margin is 10px. right margin is 5px. bottom margin is 15px. left margin is 20px.


2 Answers

document.getElementsByTagName("body")[0].style.margin.left should be:

document.getElementsByTagName("body")[0].style.marginLeft (notice the final property).

like image 53
James Allardice Avatar answered Sep 30 '22 20:09

James Allardice


Use:

document.body.style.margin = "0px 0px 0px " + xOffset + "px";
like image 42
Abdullah Jibaly Avatar answered Sep 30 '22 19:09

Abdullah Jibaly