0

I am calling .css() function at page load with the following code:

$(function(){

var positionLeft = parseInt($(".wrapper").css("margin-left"))-50;
if (isNaN(positionLeft)){
    console.log(positionLeft);
}

$("#full-wrapper").css("margin-left",(positionLeft+"px").toString()); 

});

For some reason, the positionLeft is always NaN. If I use setInterval(fn,1), and ask for a positionLeft just 1ms later, the positionLeft is as expected. What is going on here?

sanjihan
  • 5,592
  • 11
  • 54
  • 119

2 Answers2

0

I think you need to chop down that .toString() function in the end and make it just like below, as you don't really need toString() here—would work without it anyway:

$("#full-wrapper").css("margin-left", positionLeft+"px"); 

See it yourself:

$(function() {

  var positionLeft = parseInt($(".wrapper").css("margin-left")) - 50;
  if (isNaN(positionLeft)) {
    console.log(positionLeft);
  }

  $("#full-wrapper").css("margin-left", positionLeft + "px");

});
.wrapper {
  margin-left: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">.wrapper</div>
<div id="full-wrapper">#full-wrapper</div>
Rahul
  • 822
  • 6
  • 12
0

jQuery document.ready vs self calling anonymous function

Your self invoking function was a race condition and it looks like it won. Wrap your function in a document.ready() to ensure that the document is ready (initialized) before you try to access DOM element values.

Community
  • 1
  • 1
bassxzero
  • 4,838
  • 22
  • 34