views:

2210

answers:

4

Is there a way to detect the true border, padding and margin of elements from Javascript code? If you look at the following code:

<html>
    <head>
     <style>
     <!--
     .some_class {
      padding-left: 2px;
      border: 2px solid green;
     } 
     -->
     </style>
     <script>
     <!--
     function showDetails()
     {
      var elem = document.getElementById("my_div");
      alert("elem.className=" + elem.className);
      alert("elem.style.padding=" + elem.style.padding);
      alert("elem.style.paddingLeft=" + elem.style.paddingLeft);
      alert("elem.style.margin=" + elem.style.margin);
      alert("elem.style.marginLeft=" + elem.style.marginLeft);
      alert("elem.style.border=" + elem.style.border);
      alert("elem.style.borderLeft=" + elem.style.borderLeft);
     }
     -->
     </script>
    </head>
    <body>
     <div id="my_div" class="some_class" style="width: 300px; height: 300px; margin-left: 4px;">
      some text here
     </div>
     <button onclick="showDetails();">show details</button>
    </body>
</html>

you can see, if you click the button, that the padding is not reported right. Only the properties defined directly through "style" are reported back, those defined through a CSS class are not reported.

Is there a way to get back the final values of these properties? I mean the values obtained after all CSS settings are computed and applied by the browser.

Thanks.

+2  A: 

It's possible, but of course, every browser has its own implementation. Luckily, PPK has done all the hard work for us:

http://www.quirksmode.org/dom/getstyles.html

I.devries
A: 

You can adapt javascript code from mioplanet, where the resulting size of the website is calculated:

http://docs.mioplanet.com/get_web_page_size.php

joki
+2  A: 

You should use a library like JQuery to provide you these values.

http://docs.jquery.com/CSS/outerWidth http://docs.jquery.com/CSS/outerHeight

Ballsacian1
+1  A: 

With jQuery : get padding + borders of an element, write:

var wPadding = $(element).outerWidth() - $(element).width();
var hPadding = $(element).outerHeight() - $(element).Height();

or your way (but you have to state paddingLeft, paddingRight..not just 'padding' ):

<html>
<head>
    <style>
    .some_class { padding:0 0 0 20px; border: 2px solid green; }       
    </style>

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>

   <script>
    <!--
    function showDetails()
    {
            var elem = $("#my_div");
            alert("elem.className=" + elem[0].className);
            alert("elem.style.padding=" + elem.css("paddingLeft") );
    }
    -->
    </script>

</head>
<body>
    <div id="my_div" class="some_class" style="width: 300px; height: 300px; margin-left: 4px;">
            some text here
    </div>
    <button onclick="showDetails();">show details</button>
</body>

vsync