0

I'm currently making a basic drag and drop system and need to retrieve the top and left properties of the element being moved. If I do this:

var mover = document.getElementById('mover');
alert(mover.style.top);

Will alert nothing ( ' ' )

Is there any way of retrieving CSS values (in JS) without having to define them with JS first?

Oliver
  • 1,576
  • 1
  • 17
  • 31

4 Answers4

2

You will need to use getComputedStyle if you wish to retrieve properties that are computed rather than defined.

https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle

FROM the MDN link...

<script>
  function getTheStyle(){
    var elem = document.getElementById("elem-container");
    var theCSSprop = window.getComputedStyle(elem,null).getPropertyValue("height");
    document.getElementById("output").innerHTML = theCSSprop;
   }
  getTheStyle();
</script>
mccainz
  • 3,478
  • 5
  • 35
  • 45
0

You can get the position of the element as position().top, The css values can be retrieved as .css("margin-top") or .css("top")

alert($('#mover').position().top);
alert($('#mover').css("margin-top"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='mover'>dasdasD</div>

Since you dislike jQuery, here is the solution in pure JS

Update :

var mover = document.getElementById('mover');
alert(window.getComputedStyle(mover).getPropertyValue('margin-top'));
  <div id='mover'>dasdasD</div>

Tushar Gupta
  • 15,504
  • 1
  • 29
  • 47
0

There are three possible tops to worry about:

  1. The actual top position. Every element has a top resulting from the page layout, whether or not it has a computed value for the top property. Get this with getBoundingClientRect.

  2. The computed value of the CSS property top. Get this with getComputedStyle, as mentioned in other answers

  3. The current style value set on the element for top. Get this with elt.style.top as you attempted.

-2
var mover = document.getElementById('mover');
alert(mover.offsetTop);
alert(mover.offsetLeft);
chronixlol
  • 29
  • 4