0

I need to implement jQuery code on Facebook API event. Facebook API code must be placed before html code and also not inside jQuery function and calling jQuery function would be anonymous function , so I decided to create global variable, the true value of which would call the function. The problem is that the value of variable is not changed thought alert() function works in the same place of code.

Variable is defined at the very top of code just after script opens

  var not_logged_show_wall = false;

so as part of Facebook API there is else condition and alert works inside it, but value of the variable is not changed

 else{
    alert();
    not_logged_show_wall = true;
}

I checked that it's not changed by another alert in js code after html code(while the code higher was before). Also tried the same thing with $(document).ready()

No error in console log. What is wrong?

  • 1
    _“I checked that it's not changed by another alert in js code after html code”_ – FB.api works asynchronous. What you _think_ is “after” the API call therefor most likely isn’t. Go check the duplicate to learn how to handle this properly. – CBroe Jan 19 '17 at 09:46

1 Answers1

0

My guess (without fully seeing the code) is that the facebook code is wrapped in an immediately invoking function so the variable is hoisted to the top of that function and not to the window so it's actually two different variables.

if you really want it to be global (which is usually not the best) you can explicitly add it to the window, ie.

window.not_logged_show_wall = false;
else{
    alert();
    window.not_logged_show_wall = true;
}
YourGoodFriend
  • 943
  • 15
  • 22
  • shall I define variable before adding to to window or is it defined in this way ? –  Jan 18 '17 at 17:25
  • 1
    It is defined in this way. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var this explains about variable hositing and where they are defined – YourGoodFriend Jan 18 '17 at 17:25
  • didn't help unfortunately –  Jan 18 '17 at 17:30
  • 1
    have you tried moving the alert to after you change the value? `window.not_logged_show_wall = true; alert();` – YourGoodFriend Jan 18 '17 at 17:32
  • alert after changing is with True value, but old alert in script after html code (and from where jQuery function should be called ) is False –  Jan 18 '17 at 17:38
  • so Facebook code is called somehow after page is loaded ? How can I adapt my code ? –  Jan 18 '17 at 17:38
  • 1
    I would need to see more of what you are doing, I am unclear where the issue is. Are you using not_logged_show_wall somewhere else? – YourGoodFriend Jan 18 '17 at 17:40
  • no, nothing except I described. You see, False alert appeared second after True alert, which means Facebook code loads at last. I found solution by making jQuery function global and calling it from else condition. Maybe it's my fault somewhere –  Jan 18 '17 at 17:51