Reputation: 1166
I'm trying to figure out if it's possible to read a div's margins with JavaScript if those margins are set in external css
file.
So far I am able to read div's margin data when it is written as an inline style (not in CSS file but inside HTML):
(function() {
var banner = document.getElementById('banner');
var move = document.getElementById('box');
banner.onclick = function() {
alert(move.style.marginLeft);
};
})();
Here is JSFiddle: https://jsfiddle.net/b0kaLk1f/
It works well but just remove style="margin-left: 500px"
and it will stop working. I'd like to read CSS data from style.css
file rather than from inline styles.
Upvotes: 0
Views: 3723
Reputation:
Essentially you are trying to maintain state in the form of style properties, which is not a good idea. You will have to retrieve them and set them. Instead, use a class to move the extended banner back and forth. The code is shorter and simpler:
banner.onclick = function () {
ext.classList.toggle('hide_extended_banner');
};
See https://jsfiddle.net/b0kaLk1f/2/.
Upvotes: 0
Reputation: 36609
The Window.getComputedStyle()
method gives the values of all the CSS properties of an element after applying the active stylesheets
and resolving any basic computation those values may contain.
(function() {
var banner = document.getElementById('banner');
var move = document.getElementById('box');
banner.onclick = function() {
var style = window.getComputedStyle(move, null);
alert(style.marginLeft);
};
})();
#box {
margin-left: 500px;
-webkit-transition: 0.5s;
transition: 0.5s;
background: #af0000;
width: 500px;
height: 300px;
}
#banner {
border: solid 1px #000;
overflow: hidden;
width: 500px;
height: 300px;
}
<div id="banner">
<div id="box"></div>
</div>
Upvotes: 1