EN
JavaScript - element margin size in Vanilla JS
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>