0

This is what I have:

var test = '';
var img = new Image();
img.src = 'https://blahblah';
img.onload = function () {
    test = 'Sam';
}

When I console.log(test), it shows nothing. How can I assign value to test inside onload?

AmazingDayToday
  • 3,724
  • 14
  • 35
  • 67
  • Have you appended `img` to the DOM? You'll need to do that before `onload` will fire. – SimianAngel May 20 '16 at 18:15
  • @SimianAngel, yes, I did, and it is there. – AmazingDayToday May 20 '16 at 18:16
  • Hmm...once I append `img` to the DOM, I have it showing up in this CodePen: http://codepen.io/anon/pen/pyXQbv?editors=1111 – SimianAngel May 20 '16 at 18:31
  • The value is still different outside of scope. When I `console.log(test)` after adding to DOM, the value is still `''` – AmazingDayToday May 20 '16 at 18:36
  • 1
    @SimianAngel - I think the asker wants to modify a variable outside of the function's scope within the function, your codepen does not reflect this. – Austin Schmidt May 20 '16 at 18:38
  • 1
    @SeattleAls - Your goal is to modify the test variable but that variable won't exist inside the function's scope. A cheap(and dirty) fix would be making test a global variable. – Austin Schmidt May 20 '16 at 18:39
  • [This](http://stackoverflow.com/questions/2762516/changing-a-variable-out-of-scope) question might help you. This one has a good bit on what [scopes](http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript?rq=1) are. – Austin Schmidt May 20 '16 at 18:46
  • @AustinSchmidt - It's not about the scope. It's about time. See my updated JsFiddle. The value gets set correctly, but only after onload is invoked : jsfiddle.net/y7Lnp6q1/2 – Mahesh Chavda May 22 '16 at 03:48
  • @MaheshChavda Good point, the image load will be asynchronous which could easily be an issue depending on how OP lays out their code. I'd also like to point out that you made test a global in your example. Really though, OP needs to post more relevant code so that the issue can be made more clear. – Austin Schmidt May 23 '16 at 13:26

1 Answers1

0

See this jsFiddle : https://jsfiddle.net/y7Lnp6q1/1/

It depends on where you do console.log. See my comments in following code:

var test = "";
var img = new Image();
img.src = 'https://developers.google.com/search/docs/data-types/images/recipes01.png';
img.onload = function () {
    test = "Sam";
    console.log("test = " + test); // Will output "test = Sam"
}
console.log("test = " + test); // Will output "test = ", because onload is not yet triggered by this time.
Mahesh Chavda
  • 593
  • 3
  • 9