Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community of people that helps each other.

If you think you have some skills to help others

help someone and become a part of our community - List Q & A

JavaScript - element margin size in Vanilla JS

0 contributions
14 points

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>

 

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more