Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set marginLeft property using JavaScript?

Tags:

javascript

I used the following code to set the left margin for a div with id=""

document.getElementById('s4-ca').style.marginLeft = '0px';

However getting an error like Object Required!

UPDATE - My code

<script type="text/javascript">
    var groupName;
    $().SPServices({
    operation: "GetGroupCollectionFromUser",
    userLoginName: $().SPServices.SPGetCurrentUser(),
    async: false,
    completefunc: function(xData, Status) {
    $(xData.responseXML).find("[nodeName=Group]").each(function()
    {
    groupName = $(this).attr("Name");
    });
    }
    });
    if($.trim(groupName) != 'ABC')
    {
    document.getElementById('s4-leftpanel').style.display = 'none';
    document.getElementById('s4-ca').style.marginLeft = '0px';
    }
</Script>
like image 276
Jithu Avatar asked Sep 06 '26 13:09

Jithu


2 Answers

There's nothing wrong with your JavaScript, just give the <div> a matching id property, then it should work fine, i.e.

<div id="s4-ca"></div>

So there reason you're getting the error is because document.getElementById('s4-ca') doesn't find a en element with a matching id, so it's null, and you can't reference the style property on a null object.

Also, when you set the marginLeft there's no need to specify units for zero, you can use just 0.

document.getElementById('s4-ca').style.marginLeft = "0";
like image 80
Chris Fulstow Avatar answered Sep 08 '26 02:09

Chris Fulstow


Not reproducible: http://jsfiddle.net/VH2z2/

I assume you call document.getElementById before the element is available.

Either include the code on the bottom of the page or in the load event handler, e.g.

window.onload = function() {
    document.getElementById('s4-ca').style.marginLeft = '0px';
};

You should not do this if there is other JavaScript code which might set a load event handler (you would overwrite it).

like image 20
Felix Kling Avatar answered Sep 08 '26 04:09

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!