1

In this code :

$("div#info_holder").css("marginLeft", "100%");
alert(parseFloat($("#info_holder").css("marginLeft")));
alert(parseFloat(document.getElementById("info_holder").style.marginLeft));

the first alert returns 1037.78, the second alert returns 100

why is that?!

dodov
  • 5,206
  • 3
  • 34
  • 65

2 Answers2

1

It's because the jQuery version is returning the margin as pixels and the native JS is returning the value as a percentage. Take a look at this fiddle, which shoes the values before parseFloat is run.

$("div#info_holder").css("marginLeft", "100%");

console.log($("#info_holder").css("marginLeft"));
console.log(document.getElementById("info_holder").style.marginLeft);

http://jsfiddle.net/ryanbrill/wtABu/

ryanbrill
  • 1,981
  • 10
  • 13
  • 1
    Correct. Just to go 1 step further, I assume that jQuery is looking at the box model of the `div` and doing some calculations behind the scenes, hence why your getting the pixel value of `1037.78`. When using native JavaScript, I assume it's pulling the value as set, the `100%`. – Justin Chmura Dec 23 '13 at 17:31
  • You could test this by taking out parseFloat and simply showing the alert value, but this would be my suggestion. – Captain John Dec 23 '13 at 17:32
  • i see! i guess i will just use getElementById. thanks a lot! :) – dodov Dec 23 '13 at 18:04
0

$("#info_holder").css("marginLeft") returns pixel while document.getElementById("info_holder").style.marginLeft read it in percentage.

Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110
  • no, this seems a lot complicated. jQuery is made to ease things, not make them even worse. i will just use getElementById. thanks a lot, though! :) – dodov Dec 23 '13 at 18:05
  • @user3130281 exactly and jQuery is wrapper of javascript so using javascript with jQuery not something to worry or bad practice. – Zaheer Ahmed Dec 23 '13 at 18:07