views:

2503

answers:

3

I am trying to set the margin of an object from JavaScript. I am able to do it in Opera & Firefox, but the code doesn't work in Internet Explorer.

Here is the JavaScript I have:

function SetTopMargin (ObjectID, Value)
{
    document.getElementById(ObjectID).style.marginTop =  Value.toString() + "px";
}

And it is called like this:

SetTopMargin("test_div_id", 100);

So does anyone know some code that will work in Internet Explorer?

Thanks.

+1  A: 

On IE, you can use

document.getElementById(ObjectID).style.setAttribute("marginTop", Value.toString() + "px", false);

Personally, I avoid using the style object and use plain DOM when possible:

document.getElementById(ObjectID).setAttribute("style", "marginTop:" + Value.toString() + "px");
phihag
A: 

First of all, you should really use a javascript library like jQuery or Dojo. I also recommend www.debugbar.com for inspecting IE's DOM.

About your problem, elem.style = "margin: 10px" should work in IE.

Hope this helps!

BraveSirFoobar
Reason I am not using a library is that its bespoke. Built to be small and for a specific job. I am creating my own lightweight version of lightbox
Ben
A: 

Your code works in IE8 for me.

<html>
  <head>
    <script type="text/javascript"> 
    function SetTopMargin (ObjectID, Value)
    {   
      document.getElementById(ObjectID).style.marginTop =  Value.toString() + "px";
    }
    </script>
 </head>
 <body>
   <button id="btnTest" onclick="SetTopMargin('btnTest', 100);">Test</button>
 </body>
</html>

In IE6, it appears to be working as well after a very short pause.

JamesEggers
Weird...that sample works for me too.
Ben