0

I would like your help and your experience on jQuery.
So, I have a js file. Inside I have defined a object and then i use the document.ready(). Inside .ready() function i call a function, which is create some divs elements and it is defined after .ready(). The code looks like this:

gridObject = {};

document.ready(function() {
  createElements();
  console.log(gridObject);
});

function createElements() {
  var htmlBuffer = "<div class='test'>Content 1</div>" +
    "<div class='test'>Content 2</div>";
  $('.container').html(htmlBuffer);
  gridObject = getGrid();
  console.log(gridObject);
}

function getGrid() {
  return $('.test');
}

When i run this code the elements have been created, but the first console.log(gridObject) is emty, while the console.log() within createElements() return the elements. Also if i type the gridObject in Console Inspector, it returns me the object as it should...
So how this happens? Can anyone explain to me step by step how commands run and the first console return empty object, as result? And how can i deal with it?
Thank you for your time to read and answer these questions!

Jordan Soltman
  • 3,795
  • 17
  • 31
  • "_but the first console.log(gridObject) is emty_" Which first `console.log()`? Both `console.log()`'s log a value. – Ivar Jun 17 '18 at 19:39
  • the console inside document.ready() – Johnn'y Tsamis Jun 17 '18 at 20:03
  • Also i forget to mention that createElements() make a ajax call. So i am thinking that continues to run before take the response, that why the undefined object.. – Johnn'y Tsamis Jun 17 '18 at 20:17
  • Yes that makes a big difference. The example you show works synchronously while Ajax works asynchronous. – Ivar Jun 17 '18 at 20:21
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Ivar Jun 17 '18 at 20:21

0 Answers0