Languages
[Edit]
EN

JavaScript - element margin size in Vanilla JS

14 points
Created by:
Root-ssh
175020

1. Current style property example

This approach allows to get current style value (even when it was assigned with selector).

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div id="my-element" style="margin: 10px 20px 30px 40px;"></div>
  <script>
    
    var element = document.querySelector('#my-element');
    var style = element.currentStyle || window.getComputedStyle(element);

    console.log( 'margin-top:    ' + parseInt(style.marginTop)    ); // 10
    console.log( 'margin-right:  ' + parseInt(style.marginRight)  ); // 20
    console.log( 'margin-bottom: ' + parseInt(style.marginBottom) ); // 30
    console.log( 'margin-left:   ' + parseInt(style.marginLeft)   ); // 40    

  </script>
</body>
</html>

2. Reusable code example

This approach organized above code in reusable function.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>

    body {
        margin: 0;
      	background: silver;
        height: 140px;
    }

    div {
        margin: 20px 30px 40px 10px; /* [top] [right] [bottom] [left] */
        background: gray;
        width: 100px; height: 100px;
    }

  </style>
  <script type="text/javascript">

    function getMargin(element) {
		var style = element.currentStyle || window.getComputedStyle(element);

      	var result = {
            getLeft: function() {
                return parseInt(style.marginLeft);
            },
            getTop: function() {
                return parseInt(style.marginTop);
            },
            getRight: function() {
                return parseInt(style.marginRight);
            },
            getBottom: function() {
                return parseInt(style.marginBottom);
            }
        };
      
      	return result;
    }

  </script>
</head>
<body>
  <div id="my-element"></div>
  <script>
    
    var element = document.querySelector('#my-element');
    var margin = getMargin(element);

    console.log('margin-left:' + margin.getLeft());
    console.log('margin-top:' + margin.getTop());
    console.log('margin-right:' + margin.getRight());
    console.log('margin-bottom:' + margin.getBottom());

  </script>
</body>
</html>

 

Alternative titles

  1. JavaScript - element margin style size
  2. JavaScript - element margin style width
  3. JavaScript - element computed margin size
  4. JavaScript - compute element current margin size
  5. JavaScript - get element current margin size
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join