Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set the margin of an object in IE?

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?

like image 909
Cheetah Avatar asked Nov 25 '08 17:11

Cheetah


1 Answers

[Updated in 2016] On all current browsers (including IE8+), your code

document.getElementById(ObjectId).style.marginTop = Value.ToString() + 'px'; 

works fine.

On very old IE (< 8) versions, you must use this non-standard contraption instead:

document.getElementById(ObjectId).style.setAttribute(    'marginTop', Value.ToString() + 'px'); 

EDIT - From deleted comment by OP:

Note that while you can use style.setAttribute('margin-top', ..) in current IEs, 8 and older require style.setAttribute('marginTop', ..)

like image 171
phihag Avatar answered Oct 21 '22 01:10

phihag